JavaScript noob here. I've got no clue how the map1 is calculated, I've changed every element of array1 one at a time, and map1 still prints as -8. Has anyone got any link to a detailed explanation of the reduce() method? I've found none! Or can anyone please explain what's happening?
const array1 = [1, 4, 9, 16];
const map1 = array1.reduce(x => x - 2, 0);
console.log(map1); // shows -8
In Javascript,reduce accepts
array1.reduce(() => {}, initialValue);
This callback has mainly two parameters
Accumulator is just like a box which get whatever value is returned from a previous iteration. We can use this to add things from every single iteration.
So lets see a basic example:
const initialValue = 0
const answer = [1,2,3,4].reduce((acc, curr) => {
}, initialValue);
console.log('answer: ', answer);
Here we have callback function which returns nothing.
Let's see the code execution flow for this example
For the first iteration, accumulator is set to 0,
Since we aren't return anything, undefined is being returned from every iteration which sets acc = undefined on every iteration.
when all 4 iterations are completed, that accumulator is returned. (which is undefined in this case)
Example 2:
const initialValue = 0
const answer = [1,2,3,4].reduce((acc, curr) => {
return acc - 2;
}, initialValue);
console.log('answer: ', answer);
In First Iteration, acc = 0 due to initial value but at the end of this iteration, it return a value which is 0-2 = -2. acc is set to -2.
second iteration, acc-2 becomes -2-2 = -4.
third iteration, acc-2 becomes -4-2 = -6.
fourth iteration, acc-2 becomes -6-2 = -8. (last iteration, so `acc is returned and we get -8 as final result)
since we are using arrow functions, you can remove the brackets '{' '}' and 'return' keyword by writing it in single line as
const initialValue = 0
const answer = [1,2,3,4].reduce((acc, curr) => acc - 2 , initialValue);
console.log('answer: ', answer);
Both of the last two code are exactly the same with only the difference of syntactic sugar.
Hope this helps, have any questions please ask.
So put it simply, reduce takes in multiple values. First one being the previous value(in this case 0), second is the comparable value(newValue), then comes index and array.
const map1 = array1.reduce((prevValue, newValue) => newValue - 2, 0);
Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce