I’m trying to understand the differences between the .toSorted()
and .sort()
methods in JavaScript.
From my research and understanding, here’s what I know so far:
.sort():
The .sort()
method sorts the array in place and returns the reference to the same array, meaning the original array is mutated. It accepts an optional compare function to determine the sorting order.
Example:
const arr = [3, 1, 2];
arr.sort((a, b) => a - b);
console.log(arr); // output : [1, 2, 3]
.toSorted():
Based on MDN, the .toSorted()
method, returns a sorted copy of the array, leaving the original array intact. Like .sort()
, it can take an optional compare function, but it does not mutate the original array.
Example:
const arr = [3, 1, 2];
const sortedArr = arr.toSorted((a, b) => a - b); //returns a new sorted array
console.log(arr); // output: [3, 1, 2] (original array is unchanged !)
console.log(sortedArr); // output: [1, 2, 3]
Besides immutability, are there any other significant differences between these two methods?