org.sonar.l10n.javascript.rules.javascript.S4043.html Maven / Gradle / Ivy
Why is this an issue?
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();
Resources
Documentation
- MDN web docs - Array copying
methods and mutating methods
- MDN web docs - Array.prototype.reverse()
- MDN web docs - Array.prototype.sort()
- MDN web docs - Array.prototype.toReversed()
- MDN web docs - Array.prototype.toSorted()
- MDN web docs - Spread syntax
(
...
)
- MDN web docs - Array.prototype.slice()