An initial value should be provided at Array.prototype.reduce() if the array can be empty

  • REDUCE_EMPTY_ARRAY_WITHOUT_INIT
  • Error
  • High
  • No tags

This rule applies when Array.prototype.reduce() is called on an empty array without an initial value.

Starting from an initial value, Array.prototype.reduce() accumulates each element of an array using the reducer callback function. If no initial value is given, the first element of the array is used as the initial value.

Therefore, a programmer should either provide an initial value or ensure the array is not empty. Otherwise, a TypeError exception will be thrown because the result cannot be computed.

This rule also applies to Array.prototype.reduceRight().

Noncompliant Code Example

View with compliant examples side by side
function sum(numbers) {
    numbers = numbers || [];
    return numbers.reduce(add); // REDUCE_EMPTY_ARRAY_WITHOUT_INIT alarm
}

Compliant Code Example

View with noncompliant examples side by side
function sum(numbers) {
    numbers = numbers || [];
    return numbers.reduce(add, 0);
}

Version

This rule was introduced in DeepScan 1.32.0.

See

Was this documentation helpful?