In JavaScript, some Array methods do not mutate the existing array that the method was called on, but instead return a new array.
Other methods mutate the array, and their return value differs depending on the method.
reverse and sort are mutating methods and, in addition, return the altered version. This rule raises an issue when the
return values of these methods are assigned, which could lead maintainers to overlook the fact that the original array has been modified.
const reversed = a.reverse(); // Noncompliant: mutating method, no need to assign return value const sorted = b.sort(); // Noncompliant: mutating method, no need to assign return value
Remove the assignment, so that the intent of mutating the original array is clear.
a.reverse(); b.sort();
Or use non-mutating alternatives toReversed and toSorted.
const reversed = a.toReversed(); const sorted = b.toSorted();
Alternatively, change a mutating method into a non-mutating alternative using the spread syntax (…).
const reversed = [...a].reverse(); const sorted = [...b].sort();
Or slice() to create a copy first.
const reversed = a.slice().reverse(); const sorted = b.slice().sort();
The rule does not raise an issue when a sort() or reverse() call directly supplies the iterable of a for…of
loop. The loop variable receives each element, not the array returned by the call. The same applies to for await…of loops.
const values = [3, 1, 2];
for (const value of values.sort()) {
console.log(value);
}
The rule also allows a direct return of the call result. The return does not assign the result to another local variable.
function sortedValues() {
const values = [3, 1, 2];
return values.sort();
}
...)