A very general question. I was able to do the assignment for this chapter, but I did have a very quick question. I’ve pasted the exercise so you can understand my question:
- who has defined previousNumber and currentNumber…Will JavaScript always recognize those names?
- why do we have to use 0 on the last line? If I don’t include 0, it stills works.
In advance, thanks for your guidance!
var array = [4,5,6,7,8];
var singleVal = 0;
// Only change code below this line.
singleVal = array.reduce(function (previousVal, currentVal){
return previousVal + currentVal;
}, 0);
1 Like
You can name them anything you want. However it’s the position that matters. The first parameter holds the previous return value of the callback function (or the initial value, more on that below). The second one holds the current element while iterating over the array.
It’s the optional initial value. If you provide an initial value, .reduce
will start iterating over the array from the first element, and previousVal
will hold that value. If you didn’t provide one, the initial value will be the array’s first element, and .reduce
will start iterating from the second element.
Note that if you didn’t provide an initial value, .reduce
will throw an error if the array is empty.
2 Likes
@kevcomedia @SkyC @DanCouper Thank you all so very much!!! This is very helpful!!!