Difference between sort() and toSorted()
Sathik

Sathik @_sathikbasha

Location:
Tamilnadu, India.
Joined:
Dec 17, 2018

Difference between sort() and toSorted()

Publish Date: Aug 7 '23
0 2

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

Comments 2 total

  • Pedro Bruneli
    Pedro BruneliAug 7, 2023

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

    Image description

    • Sathik
      SathikAug 8, 2023

      @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.

Add comment