What is Reduce in JavaScript ?
The reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator.
Syntax:
array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue);
Parameters:
callback
: A function that is called once for each element in the array.accumulator
: The accumulated result of the previous callback invocation orinitialValue
if provided.currentValue
: The current element being processed in the array.currentIndex
: (Optional) The index of the current element being processed.array
: (Optional) The arrayreduce()
was called upon.
initialValue
: (Optional) A value to use as the initial accumulator. If not provided, the first element of the array is used as the initial accumulator.
Example: Here, the reduce()
method is used to add up all the elements of the numbers
array. The callback function takes two parameters (accumulator
and currentValue
) and returns the sum of these values.
Javascript
let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce( function (accumulator, currentValue) { return accumulator + currentValue; }, 0); console.log(sum); // Output: 15 |
Output
15
Contact Us