The .sort() method mutates the original array in place.
Using .toSorted() instead returns a new sorted array without modifying the original, making code more predictable and avoiding unintended side effects.
Sorts an array in place.
This method mutates the array and returns a reference to the same array.
@param ―
compareFn Function used to determine the order of the elements. It is expected to return
a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.
Sorts an array in place.
This method mutates the array and returns a reference to the same array.
@param ―
compareFn Function used to determine the order of the elements. It is expected to return
a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.
Sorts an array in place.
This method mutates the array and returns a reference to the same array.
@param ―
compareFn Function used to determine the order of the elements. It is expected to return
a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.
Returns a copy of an array with its elements sorted.
@param ―
compareFn Function used to determine the order of the elements. It is expected to return
a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.
[11, 2, 22, 1].toSorted((a, b)=> a - b) // [1, 2, 11, 22]
Returns a copy of an array with its elements sorted.
@param ―
compareFn Function used to determine the order of the elements. It is expected to return
a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.
[11, 2, 22, 1].toSorted((a, b)=> a - b) // [1, 2, 11, 22]
Sorts an array in place.
This method mutates the array and returns a reference to the same array.
@param ―
compareFn Function used to determine the order of the elements. It is expected to return
a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.
If you intentionally want to mutate the original array in place, or if you’re working in an environment that doesn’t support .toSorted() (ES2023+), you may want to disable this rule.
Note that .sort() is still allowed when used as a standalone expression statement since the mutation is likely intentional in that case.