unicorn/no-array-reverse
Require toReversed() instead of reverse(), which changes the array
has suggestions
reverse() reverses the array in place and returns that same array. After const newestFirst = posts.reverse(), posts is reversed too. toReversed() returns a new array and leaves the original alone.
--fix-suggestions replaces reverse with toReversed.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/no-array-reverse" = "error" # or "warn"Every option, set to its default:
bunfig.toml
[lint.rules]
"unicorn/no-array-reverse" = ["error", {
allowExpressionStatement = true,
}]Examples#
example.js1 problem
const newestFirst = posts.reverseUse Array#toReversed() instead of Array#reverse().();Copying the array first is reported too, because toReversed() already makes a copy:
example.js1 problem
const newestFirst = [...posts].reverseUse Array#toReversed() instead of Array#reverse().();example.jsNo problems
const newestFirst = posts.toReversed();A call used as a standalone statement is allowed by default. Nothing uses the result, so changing the array is the point:
example.jsNo problems
posts.reverse();Options#
| Option | Default | What it does |
|---|---|---|
allowExpressionStatement | true | Allow array.reverse(); as a standalone statement. |
example.jswith
{ "allowExpressionStatement": false }1 problemposts.reverseUse Array#toReversed() instead of Array#reverse().();When not to use it#
toReversed() is part of ES2023. Turn the rule off if your code needs to run somewhere that doesn't have it.