Quick Overview
`.reduce()` carries an accumulator across the array, and the initial value decides the shape of the result: `0` gives a number, `{}` an object, `[]` an array. Omit it and the first element becomes the seed.
The .reduce() method executes a user-supplied "reducer" callback function on each element of the array, passing in the return value from the calculation on the preceding element.
.reduce() is the swiss army knife of array methods. It can compute total sums, flatten nested arrays, or build complex objects from array streams in a single pass.
Pass a callback function taking (accumulator, currentValue) and an explicit initial accumulator starting value:
const cartPrices = [15, 25, 10];
// Sum total prices with initial accumulator 0
const totalCost = cartPrices.reduce((sum, price) => {
return sum + price;
}, 0);
console.log(totalCost); // 50
You can use .reduce() with an empty object {} initial value to count occurrences or group items:
const votes = ["yes", "no", "yes", "yes", "no"];
const tally = votes.reduce((acc, vote) => {
acc[vote] = (acc[vote] || 0) + 1;
return acc; // Must return the updated accumulator!
}, {});
console.log(tally); // { yes: 3, no: 2 }
.reduce(), array element 0 becomes the initial accumulator and iteration starts at index 1. On empty arrays, omitting the initial value throws an uncaught TypeError: Reduce of empty array with no initial value!Write it yourself. The tests below run against your code.
Always supply an initial accumulator value to .reduce(). Next, let's explore clean variable unpacking with Destructuring!
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.