org.sonar.l10n.javascript.rules.javascript.S3796.html Maven / Gradle / Ivy
Why is this an issue?
In JavaScript, many array methods take a callback function as an argument. These methods are designed to transform or filter arrays based on the
logic provided in the callback function. The callback function is called sequentially, and the return value of the callback function is used to
determine the return value of the Array
method.
If the callback function does not return a value, the array method may not work as expected and is most likely a mistake.
This rule applies to the following methods of an array:
-
Array.from
-
Array.prototype.every
-
Array.prototype.filter
-
Array.prototype.find
-
Array.prototype.findLast
-
Array.prototype.findIndex
-
Array.prototype.findLastIndex
-
Array.prototype.map
-
Array.prototype.flatMap
-
Array.prototype.reduce
-
Array.prototype.reduceRight
-
Array.prototype.some
-
Array.prototype.sort
-
Array.prototype.toSorted
If there is no return
, the callback will implicitly return undefined
, which may cause unexpected behavior or errors in
the code.
let arr = ["a", "b", "c"];
let merged = arr.reduce(function(a, b) {
a.concat(b); // Noncompliant: No return statement, will result in TypeError
});
Always add a return statement to the callback function passed to the array method.
let arr = ["a", "b", "c"];
let merged = arr.reduce(function(a, b) {
return a.concat(b);
});
Resources
Documentation
- MDN web docs - Array
© 2015 - 2024 Weber Informatics LLC | Privacy Policy