Comparing sort() and toSorted() functions

Photo by Jess Bailey on Unsplash

Comparing sort() and toSorted() functions

sort() vs toSorted() comparison

Table of contents

The Sorting Functions

The sort() and toSorted() functions are used primarily on arrays. Both functions sort an array by converting the elements to string i.e by default the sorting is string based. Both the functions can take predicate as sorting strategy.

The principle difference between sort() and toSorted() functions are as follows

sort()toSorted()
Sorts the host arrayReturns a new sorted array
The host array is updatedThe host array is not sorted

Let's understand the difference with help of code

// difference between sort and toSorted

let arr = [7,3,1,4,9,2];
let arr2 = [91,74,19,7,190,3];

// sort modifies the host itself - string based sort
let arr3 = arr.sort();
console.log("sort", arr, arr3);

 arr = [7,34,11,49,96,2,1];
 arr3 = arr.sort();
 console.log("sort", arr,arr3);
 arr3 = arr.sort((a,b) => a-b);
 console.log("sort-predicate", arr,arr3);



//toSorted returns a new array - string sort
let arr4 = arr2.toSorted();
console.log("toSorted", arr2, arr4);
// with predicate
arr2 = [91,74,19,7,190,3];
arr4 = arr2.toSorted((a,b)=> a-b); 
console.log("toSorted - predicate", arr2, arr4);

In the above code the when sort() function is used it updates the host array but when toSorted() function is used it returns a sorted array and host array is not updated.