Reduce Method in JavaScript

Nilesh Saini
2 min readMay 8, 2022

--

Concise explanation of reduce method in Js

Photo by Zdeněk Macháček on Unsplash
  1. Accepts a callback function and an optional second parameter.
  2. Iterates through an array.
  3. Runs a callback on each value in the array.
  4. The first parameter to the callback is either the first value in the array or the optional second parameter.
  5. The first parameter to the callback is often called “accumulator”.
  6. The returned value from the callback becomes the new value of the accumulator.
array.reduce(function(accumulator, nextValue, index, array){
// statements
}, optional second parameter)

Parameters:

  • Callback function: The function that runs on each value of the given array.
  • Accumulator: First value in the array or the optional second parameter given.
  • nextValue: Second value in the array or the first value if the optional parameter is passed.
  • Index: Each index in the array.
  • Array: The entire array on which reduce method is applied.

Examples:

  1. Print the sum of all the elements of the array using the reduce method.

Output: 15

Explanation:

  • Since no second parameter was given so accumulator’s initial value will be the first value of the array i.e. 1.
  • The second value is 2 and we add both the values and return the sum.
  • This returned sum is going to be the next value of the accumulator.
  • These steps will be repeated till the last element of the array.
  • The total sum of the array is returned.

2. Adding a second parameter.

Output: 25

Explanation:

  • In this example, we are given an additional parameter in the reduce function. (10)
  • So, the initial value of the accumulator is 10, and the next value is 1. Return the sum of both of these values.
  • The sum is going to be the new value of the accumulator.
  • These steps will be repeated till the last element of the array.
  • The total sum will be returned.

3. Using the reduce method in strings.

Output: ‘TBBT characters are Sheldon Raj Penny Amy Howard’

Explanation:

  • In this example, we are given an additional parameter in the reduce function. (‘TBBT characters are’)
  • So, the initial value of the accumulator is ‘TBBT characters are’, and the next value is ‘Raj’. Return the sum of both of these strings.
  • This new string is going to be the new accumulator.
  • These steps will be repeated till the last string of the array.
  • A single string with all array elements concatenated will be returned.

4. Create a function to add only odd numbers in the array.

--

--

Nilesh Saini

Web Developer/ Front-end engineer who loves solving Rubik's Cube