34 lines
1.6 KiB
Plaintext
Raw Normal View History

== 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.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
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()`.
[source,javascript,diff-id=1,diff-type=compliant]
----
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 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce[Array.prototype.reduce()]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Reduce_of_empty_array_with_no_initial_value[TypeError: Reduce of empty array with no initial value]