Table of contents
1.
Introduction
2.
Syntax
3.
Parameters
4.
Return value
5.
Exceptions
6.
Examples
7.
When to not use reduce()
8.
Supported Browsers
9.
Frequently Asked Questions
9.1.
What happens if I don't provide an initial value?
9.2.
Can reduce() be used on an empty array?
9.3.
Is reduce() immutable? Does it change the original array?
10.
Conclusion
Last Updated: Oct 30, 2024
Easy

JavaScript Array reduce() Method

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JavaScript arrays have many useful methods that make it easy to perform operations on the elements. One of the most powerful is the reduce() method. It lets you take an array and reduce it down to a single value by applying a function to each element. 

JavaScript Array reduce() Method

In this article, we'll learn all about the syntax of reduce(), what parameters it takes, the return value, & see plenty of examples of how to use it effectively. Apart from all these, we will explain some edge cases to watch out for & discuss when reduce() might not be the best choice.

Syntax

The syntax of reduce() method is:

array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])


The reduce() method executes the callback function once for each element in the array (excluding holes). The callback function takes four arguments:
 

- `accumulator`: The accumulated value previously returned in the last invocation of the callback, or `initialValue` if supplied.

- `currentValue`: The current element being processed in the array. 

- `index` (Optional): The index of the current element being processed in the array.

- `array` (Optional): The array reduce() was called upon.
 

You can also pass an optional `initialValue` as the second argument to reduce(). If it is provided, it will be used as the initial accumulator value in the first call to the callback.

Parameters

The reduce() method takes two parameters:
 

1. `callback`: The function to execute on each element in the array. It takes four arguments:

   - `accumulator`: The value resulting from the previous call to callback. On the first call, it's either the `initialValue` if provided or the first value in the array. 

   - `currentValue`: The value of the current element.

   - `index` (Optional): The index of currentValue in the array.

   - `array` (Optional): The array being traversed.

 

2. `initialValue` (Optional): A value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used & skipped. Calling reduce() on an empty array without an initial value will throw an error.


Note: The callback function should return the accumulated value, which will be provided as an argument in the next call to the callback. After the last iteration, the final accumulated value is returned as the result of reduce().

Return value

The reduce() method returns a single value, which is the result of running the "reducer" callback function on each element of the array.

The final value is calculated like this:


1. If an `initialValue` is provided:

   - The accumulator starts as the `initialValue`.

   - The callback is executed for each element, with the accumulator being the return value of the previous callback execution.

   - After the last iteration, the final accumulator value is returned.


2. If no `initialValue` is provided: 

   - The accumulator starts as the first value in the array.

   - The callback starts executing from the 2nd element (index 1).

   - After the last iteration, the final accumulator value is returned.


So, in both cases, what's returned is the final accumulated value that results from running the callback on each element. This could be a number, string, object, or any other type, depending on what the reducer function does.

Exceptions

There are a couple of exceptions which we need to take care of while using reduce():

1. Calling reduce() on an empty array without an `initialValue` will throw a `TypeError`. 
 

For example:

[].reduce((acc, val) => acc + val); // TypeError: Reduce of empty array with no initial value


If the array can be empty and you want the reducer to return a specific value, like 0 or an empty object, always provide an `initialValue`.


2. The reducer function must return a value for each iteration. If you forget a return statement, `undefined` will be returned & used as the accumulator in the next iteration, likely causing unexpected results or an error. For example:

[1, 2, 3].reduce((acc, val) => {
  // No return statement!
  acc + val;
}); // undefined


You can avoid these exceptions as long as you provide a default `initialValue` when needed and always return a value from your reducer callback.

Examples

Now, let’s see a few examples to see how we can use reduce():

1. Summing numbers:

const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, val) => acc + val, 0);
console.log(sum);
You can also try this code with Online Javascript Compiler
Run Code


Output

10


2. Flattening arrays:

const nested = [[1, 2], [3, 4], [5, 6]];
const flat = nested.reduce((acc, val) => acc.concat(val), []);
console.log(flat); 
You can also try this code with Online Javascript Compiler
Run Code


Output

[1, 2, 3, 4, 5, 6]


3. Grouping objects by a property:

const people = [
  { name: 'Rahul', age: 21 },
  { name: 'Harsh', age: 20 },
  { name: 'Sanjana', age: 20 }
];
const groupedByAge = people.reduce((acc, val) => {
  const key = val.age;
  if (!acc[key]) {
    acc[key] = [];
  }
  acc[key].push(val);
  return acc;
}, {});

console.log(groupedByAge);
You can also try this code with Online Javascript Compiler
Run Code


Output

{ '20': [ { name: 'Harsh', age: 20 }, { name: 'Sanjana', age: 20 } ],
  '21': [ { name: 'Rahul', age: 21 } ] }


Note: These are just a few possibilities. Reduce is a versatile tool that can be used to transform arrays into any kind of value. The important factor is that the reducer callback returns the new accumulated value on each iteration. 

When to not use reduce()

While reduce() is powerful, it's not always the most preferred choice. Let’s discuss some situations where you might don't want to use this function:

1. When a simple loop would suffice: If you're just doing something straightforward like creating a new array or finding a single value, a regular for loop or a method like map() or find() might be more readable & faster.
 

2. When you're not returning a value from the callback: If your reducer function isn't returning a new accumulated value each time, it's a sign that reduce() might not be the right tool. Reduce is for boiling an array down to a single value, not for performing side effects.
 

3. When performance is critical on large arrays: Reduce has to call your function once for every element. On very large arrays, this can lead to significant overhead compared to a regular loop.
 

4. When you need to break out of the loop early: Reduce always traverses the entire array (unless you throw an error). If you often need to stop processing after finding a certain value, a regular loop with a break statement might be more efficient.


Important Point: Remember, just because you can use reduce() doesn't always mean you should. Consider readability and performance in your specific use case.

Supported Browsers

The reduce() method is widely supported across modern browsers:

- Chrome: 3+

- Edge: 12+

- Firefox: 3+

- Internet Explorer: 9+

- Opera: 10.5+

- Safari: 4+


It's also supported in Node.js & other JavaScript runtime environments.

Frequently Asked Questions

What happens if I don't provide an initial value?

If no initial value is provided, reduce() will use the first element of the array as the initial accumulator value & start iterating from the second element.

Can reduce() be used on an empty array?

Yes, as long as you provide an initial value. If you call reduce() on an empty array without an initial value, it will throw a TypeError.

Is reduce() immutable? Does it change the original array?

Yes, reduce() is immutable. It does not modify the original array but instead returns a new value based on the accumulator & the elements processed.

Conclusion

In this article, we've learned about a very important function: the JavaScript reduce() method. We've discussed its syntax, parameters, return value, and common use cases with examples. We've also discussed some edge cases we must take care of and situations where reduce() might not be the best choice. 

You can also check out our other blogs on Code360.

Live masterclass