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:
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);
});