JavaScript Array reduce Without Initial Value
When using JavaScript’s Array.prototype.reduce() method
without supplying an initialValue, the method modifies how
it assigns initial iteration values, how many times the callback
executes, and how it handles edge cases. This article explains the exact
behavior of reduce() when the initial value is omitted,
detailing the accumulator assignment, iteration index start, and the
critical error thrown on empty arrays.
Accumulator and Index Assignment
When you omit the initialValue argument in
reduce(callback):
- Accumulator Value: The
accumulatorparameter in the first callback execution is automatically set to the first element in the array (array[0]). - Current Value: The
currentValueparameter is set to the second element in the array (array[1]). - Starting Index: The execution begins at index
1rather than index0.
Because the first element is consumed as the accumulator, the
callback runs array.length - 1 times instead of
array.length times.
const numbers = [10, 20, 30];
const sum = numbers.reduce((acc, curr, index) => {
console.log(`Index: ${index}, Acc: ${acc}, Curr: ${curr}`);
return acc + curr;
});
// Output:
// Index: 1, Acc: 10, Curr: 20
// Index: 2, Acc: 30, Curr: 30
// Result: 60Behavior with a Single-Element Array
If the array contains only one element and no
initialValue is provided, reduce() will
immediately return that single element without calling the callback
function at all.
const single = [42];
const result = single.reduce((acc, curr) => acc + curr);
console.log(result); // 42 (callback is never executed)Behavior with an Empty Array
Calling reduce() on an empty array without an
initialValue results in a runtime error. JavaScript cannot
determine an initial accumulator value, throwing a
TypeError.
const empty = [];
empty.reduce((acc, curr) => acc + curr);
// Uncaught TypeError: Reduce of empty array with no initial valueProviding an initialValue prevents this error by
allowing reduce() to return the initial value directly when
the array is empty.
Summary of Differences
| Feature | With initialValue |
Without initialValue |
|---|---|---|
| Initial Accumulator | Equal to initialValue |
Equal to array[0] |
| Initial Current Value | Equal to array[0] |
Equal to array[1] |
| Starting Index | 0 |
1 |
| Total Callback Runs | array.length |
array.length - 1 |
| Empty Array Result | Returns initialValue |
Throws TypeError |