DEV Community

Sathik
Sathik

Posted on

Difference between sort() and toSorted()

In javascript, both method do the same job, except original array mutation.

sort() method mutate the original array. No need to store the return value in variable.

var arr = [1,2,1000];
arr.sort();
console.log(arr);
// console.log() => 1, 1000, 2
Enter fullscreen mode Exit fullscreen mode

toSorted() method does not mutate the original array. Need to store the return value in variable.

var arr = [1,2,1000];
var sortedArr = arr.toSorted();
console.log(sortedArr);
// console.log() => 1, 1000, 2
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
pedrobruneli profile image
Pedro Bruneli

One thing to add about the both function:
sort() is way more perf than toSorted()

Image description

Collapse
 
_sathikbasha profile image
Sathik

@pedrobruneli Yes, 100% Agree.
Reason behind the performance and memory usage, sort() does not create the new Array while perform the operation. but toSorted() create the new Array to perform the operation.