Array.prototype.reduce()

Examples

Here are some examples of how to use the reduce() method:

// Calculate the sum of an array of numbers
const numbers = [1, 2, 3, 4, 5]
const sum = numbers.reduce((total, number) => total + number, 0)
console.log(sum) // 15
// Concatenate an array of strings
const words = ['the', 'quick', 'brown', 'fox']
const sentence = words.reduce((string, word) => string + ' ' + word)
console.log(sentence) // "the quick brown fox"
// Calculate the average of an array of numbers
const average = numbers.reduce((total, number, index, array) => {
  total += number
  if (index === array.length - 1) {
    return total / array.length
  }
  return total
}, 0)
console.log(average) // 3

Syntax

The syntax for the reduce() method is as follows:

array.reduce(function (total, currentValue, currentIndex, array) {
  // code to be executed
}, initialValue)

The reduce() method takes in a callback function as its first argument. This function is called for each element in the array, and takes in four arguments:

  • total: the accumulated value, which is initialized to the initialValue argument (if provided) or the first element in the array (if no initialValue is provided)
  • currentValue: the current element being processed in the array
  • currentIndex: the index of the current element being processed in the array
  • array: the array the reduce() method was called on

The callback function should return the accumulated value for the next iteration.

Description

The reduce() method executes a provided function for each value of the array (from left-to-right), and the return value of the function is used as the accumulator for the next call. The initial value for the accumulator can be provided as an optional second argument to the reduce() method.

For example, consider the following code:

const numbers = [1, 2, 3, 4, 5]
const sum = numbers.reduce((total, number) => total + number, 0)
console.log(sum) // 15

In this case, the reduce() method is called on the numbers array with a callback function that adds the current element to the total. The initial value for the accumulator is set to 0. The reduce() method then iterates over the numbers array, starting with the first element (1). The callback function is called with the arguments total (0) and number (1). The callback function returns 1, which becomes the new value of the accumulator.

The reduce() method then moves on to the next element in the array (2) and calls the callback function with the arguments total (1) and number (2). The callback function returns 3, which becomes the new value of the accumulator. This process continues until all elements in the array have been processed, and the final value of the accumulator (15) is returned.

Specifications

The reduce() method is specified in the ECMAScript specification, which is the standard for modern JavaScript. According to the specification, the reduce() method should behave as follows:

  • If the array argument to the reduce() method is an empty array and no initialValue argument is provided, a TypeError should be thrown.
  • If the array argument to the reduce() method is an empty array and an initialValue argument is provided, the initialValue should be returned.
  • If the array argument to the reduce() method is not an empty array and no initialValue argument is provided, the reduce() method should call the callback function with four arguments: the first element of the array as the total argument, the second element of the array as the currentValue argument, and the index of the second element as the currentIndex argument, and the array as the array argument.
  • If the array argument to the reduce() method is not an empty array and an initialValue argument is provided, the reduce() method should call the callback function with four arguments: the initialValue as the total argument, the first element of the array as the currentValue argument, and the index of the first element as the currentIndex argument, and the array as the array argument.

Browser Compatibility

The reduce() method is supported in all modern browsers, including Internet Explorer 9 and above. You can use the reduce() method without worrying about compatibility issues in most cases.

Similar Methods

There are several other array methods in JavaScript that are similar to the reduce() method, such as map() and filter(). The map() method creates a new array by calling a provided function on each element in the array, while the ``filter()` method creates a new array with all elements that pass a provided test function.

In contrast to these methods, the reduce() method returns a single value rather than a new array. This makes it useful for tasks such as calculating the sum of an array or concatenating an array of strings, but it is not as suitable for tasks that require creating a new array. For example, if you want to create a new array with the squared values of the elements in an array, you would use the map() method rather than the reduce() method.

Overall, the reduce() method is a useful and powerful tool for working with arrays in JavaScript. Whether you need to calculate the sum of an array, concatenate an array of strings, or perform some other operation on an array, the reduce() method is a flexible and efficient way to do so.