The reduce function in Javascript is a function which executes a callback function using parameters which are: an accumulator, which adds the return value, and the current value which is value that the pointer is currently on. The reduce function also allows us to add an initial value to use.

Examples

const array = [10, 20, 30, 40];
const initialValue = 0;

//0 + (10 * 2) First iteration
//20 + (20 * 2) Second iteration
//60 + (30 * 2) Third iteration
//120 + (40 * 2) Fourth iteration
const doubleValues = array.reduce((accumulator, currentValue) => accumulator + (currentValue * 2), initialValue)

console.log(doubleValues); //200

If we want to return the value of each element doubled in an array, we would do the following:

const array = [10, 20, 30, 40];

const doubleValues = array.reduce((accumulator, currentValue) => {
accumulator.push(currentValue * 2)
return accumulator;
}, []);

console.log(doubleValues); //[20, 40, 60, 80]

If we want to include the initial value in the array from the first example, we would do the following:

const array = [10, 20, 30, 40];
const initialValue = 0;

const doubleValues = array.reduce((accumulator, currentValue) => {
accumulator.push(currentValue * 2)
return accumulator;
}, [initialValue]);

console.log(doubleValues); //[0, 20, 40, 60, 80]