org.sonar.l10n.javascript.rules.javascript.S6959.html Maven / Gradle / Ivy
Why is this an issue?
The Array.prototype.reduce()
method in JavaScript is used to apply a function against an accumulator and each element in the array
(from left to right) to reduce it to a single output value. It is a convenient method that can simplify logic in your code.
However, it’s important to always provide an initial value as the second argument to reduce()
. The initial value is used as the first
argument to the first call of the callback function. If no initial value is supplied, JavaScript will use the first element of the array as the
initial accumulator value and start iterating at the second element.
This can lead to runtime errors if the array is empty, as reduce()
will throw a TypeError.
function sum(xs) {
return xs.reduce((acc, current) => acc + current); // Noncompliant
}
console.log(sum([1, 2, 3, 4, 5])); // Prints 15
console.log(sum([])); // TypeError: Reduce of empty array with no initial value
To fix this, always provide an initial value as the second argument to reduce()
.
function sum(xs) {
return xs.reduce((acc, current) => acc + current, 0);
}
console.log(sum([1, 2, 3, 4, 5])); // Prints 15
console.log(sum([])); // Prints 0
Resources
Documentation
- MDN web docs - Array.prototype.reduce()
- MDN web docs - TypeError: Reduce of
empty array with no initial value