JavaScript Interview Question #43

What does reduce() do in JavaScript?

Objects, Arrays & Core Data Handling Junior Beginner

Quick Interview Answer

reduce processes an array and combines its elements into a single accumulated result. The result can be a number, string, object, array, map-like structure, or another value.

Detailed Explanation

reduce processes an array and combines its elements into a single accumulated result. The result can be a number, string, object, array, map-like structure, or another value.

The callback receives the accumulator and current element. Providing an explicit initial value is usually clearer and avoids errors when reducing an empty array.

Code Example

const prices = [100, 200, 300];

const total = prices.reduce(
    (sum, price) => sum + price,
    0
);

console.log(total); // 600