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
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
Top comments (2)
One thing to add about the both function:
sort() is way more perf than toSorted()
@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.