All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.javascript.rules.javascript.S6959.html Maven / Gradle / Ivy

There is a newer version: 10.20.0.29356
Show newest version

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





© 2015 - 2024 Weber Informatics LLC | Privacy Policy