what is array reduce() in JavaScript

When using reduce() it goes through every element in an array and allows you to combine them into a single value.

reduce() takes in a function that runs on every element has these parameters:

An example of using reduce() would be to add up all elements in an array to one value.

JavaScript

const numbers = [1, 2, 3, 4, 5];
const addAllNumbers = numbers.reduce(
    (previousValue, currentValue, currentIndex, array) => {
        console.log(previousValue, currentValue, currentIndex, array);
        // 1, 2, 1, [1, 2, 3, 4, 5]
        // 3, 3, 2, [1, 2, 3, 4, 5]
        // 6, 4, 3, [1, 2, 3, 4, 5]
        // 10, 5, 4, [1, 2, 3, 4, 5]
        return previousValue + currentValue;
    }
);

console.log(addAllNumbers); // 15
console.log(numbers); // [1, 2, 3, 4, 5]

The previous value can be set by passing in another argument.

When the first reduce() function call is made the current value and current index will be the first element instead of the second element in the array.

JavaScript

const numbers = [1, 2, 3, 4, 5];
const addAllNumbers = numbers.reduce(
    (previousValue, currentValue, currentIndex) => {
        console.log(previousValue, currentValue, currentIndex);
        // 10 1 0
        // 11 2 1
        // 13 3 2
        // 16 4 3
        // 20 5 4
        return previousValue + currentValue;
    },
    10
);

console.log(addAllNumbers); // 15
console.log(numbers); // [1, 2, 3, 4, 5]

summary of reduce()

Runs a function on every element in an array and allows you to turn the array into a single value. The initial value can be set by passing in another argument.

In the end the final function call returned value is used.

html
css
javascript
Tracking changes with Git

Now that we know how to setup Git, lets see how we can track changes.

javascript
what is array map() in JavaScript

map() allows you to make changes to every element in an array without modifying the original array.