reduce() method in JavaScript

Introduction

In this tutorial, you will learn the concept of the reduce() method. It is an array function, and it is used to transform an array into a single value.

It processes each element of the array and accumulates the result into one final output.

Syntax of reduce()


array.reduce(callback, initialValue);

Explanation:

callback => Function executed for each array element.

accumulator => Stores the result of the previous iteration.

currentValue => Current element being processed.

initialValue => Starting value of the accumulator.

Example 1: Sum of Numbers

One of the most common uses of reduce() is calculating the sum of an array.

Example:


const numbers = [10, 20, 30, 40];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum);

Output

100

Explanation:

Step Accumulator Current Value Result
1 0 10 10
2 10 20 30
3 30 30 60
4 60 40 100

Example 2: Finding Maximum Value


const numbers = [5, 10, 2, 25, 8];
const max = numbers.reduce((acc, num) => {
  return num > acc ? num : acc;
});
console.log(max);

Output:

25

reduce() vs map() vs forEach()

Method Purpose Return Value
map() Transform array elements New array
forEach() Execute function on each element Undefined
reduce() Convert array into single value Single result

When to use the reduce() method?

There are many options to use the reduce() method

  1. Calculate totals
  2. Aggregate values
  3. Convert arrays into objects
  4. Combine array data into a single value

Example:


const prices = [100, 200, 300];
const total = prices.reduce((acc, price) => acc + price, 0);
console.log(total);

Common Mistake with reduce()

Many beginners forget to provide an initial value.

Incorrect


array.reduce((acc, value) => acc + value);

Correct


array.reduce((acc, value) => acc + value, 0);

Note: Providing an initial value prevents unexpected errors.

Real Life Example of reduce() in JavaScript

Shopping Cart Total Price

When you are working on E-Commerce App, and you are calculating the total price of items in a shopping cart, then we use reduce().

Example:


const cart = [
  { product: "Laptop", price: 60000 },
  { product: "Mouse", price: 1000 },
  { product: "Keyboard", price: 1500 },
  { product: "Headphones", price: 2500 }
];

const totalPrice = cart.reduce((total, item) => {
  return total + item.price;
}, 0);

console.log("Total Price:", totalPrice);

Output:

Total Price: 65000

Explanation:

  1. total → Accumulator that stores the running total.
  2. item → Current object from the array.
  3. 0 → Initial value of the accumulator.
  4. reduce() loops through every item and adds the price to the total.

Other Real World Scenario

There are many Real World Scenario are:

  1. E-commerce websites
  2. Food delivery apps
  3. Online booking platforms

Interview Questions

Q 1: What is the reduce() method in JavaScript?
Ans: The reduce() method is used to reduce an array into a single value by applying a function to each element of the array.
Q 2: What does the reduce() method return?
Ans: The reduce() method returns one final value, which can be:
A number
A string
An object
An array
Q 3: What is an accumulator in reduce()?
Ans: The accumulator is the value that stores the result after each iteration.
Example:
const numbers = [1, 2, 3];
numbers.reduce((total, num) => total + num, 0);
Q 4: Is reduce() available for all arrays?
Ans: Yes, reduce() is a built-in JavaScript array method, so it can be used with any JavaScript array.

Conclusion

The reduce() method is an array function in JavaScript, and it is used to transform an entire array into a single value. It works by repeatedly applying a function to each element of the array while maintaining an accumulator.

Master JavaScript Array Methods