Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Reduce an empty array

People also ask

Can you call reduce on a empty array?

The JavaScript exception "reduce of empty array with no initial value" occurs when a reduce function is used.

What happens when you reduce an empty array?

This error is raised if an empty array is provided to the reduce() method because no initial value can be returned in this case. Example 1: In this example, the filter method removes all elements, So the reduce method applies to empty array and error occurred.

How do you reduce an array in JavaScript?

JavaScript Array reduce()The reduce() method executes a reducer function for array element. The reduce() method returns a single value: the function's accumulated result. The reduce() method does not execute the function for empty array elements. The reduce() method does not change the original array.

What is reduce () in JavaScript?

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( function(total, currentValue, currentIndex, arr), initialValue )


The second parameter is for initial value.

[].reduce(function(previousValue, currentValue){
  return Number(previousValue) + Number(currentValue);
}, 0);

or using ES6:

[].reduce( (previousValue, currentValue) => previousValue + currentValue, 0);

Both behaviors are according to the spec.

You cannot reduce an empty array unless you explicitly provide an initial "accumulated" value as the second argument:

If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second. It is a TypeError if the array contains no elements and initialValue is not provided.

If the array has at least one element then providing an initial value is optional. However, if one is not provided then the first element of the array is used as the initial value and reduce continues to process the rest of the array elements by invoking your callback. In your case the array only contains a single element, so that element becomes the initial value and also final value, since there are no more elements to be processed through the callback.