Compare .sort() and .toSorted() methods
--
I want to take a closer look at these both JavaScript Array methods. What is the key difference and why we needed the .toSorted() method so much?
Let’s open a browser console. Below I give you a sample of data I will work with right now.
const ORIGINAL_DATA = [
"Dog",
"Cat",
"Hamster",
"Lion",
"Cow",
"Pig",
"Sheep",
"Zebra",
"Moose",
"Tiger",
"Shark",
"Shrimp",
];
First, use method .toSorted() and assign the result to a variable. Then console sorted the array. It seems everything works fine.
const toSortedReference = ORIGINAL_DATA.toSorted();
In the next step, use the .sort() method and assign the result to another variable. Repeat the sort check.
const sortReference = ORIGINAL_DATA.sort();
At first glance, the methods work identically because the difference is visible when we compare object references.
As you can see, references of the sortReference array and the toSortedReference array are not equal. It means that even if we see the same output in the console, underneath there are different arrays. What would be the result when we compare their references with the reference of the original array?
And here is the clue to the difference between these two JavaScript methods. The sort method and the original data have the same reference, which means they are the same array. The opposite is true for the toSorted. This method makes a copy of the original array and leaves the original data without any modification. We can recognize similar approaches in the filter, map, and reduce methods. It is good practice not to touch the original data and keep it unchanged.
That’s why I asked you to use the toSorted method first. If we did the opposite, the array would be already sorted because the original data would be overwritten by the sort method. Output would be the same, but in this case, we are sure that both work.
That’s all for today.
I invite you to read my related article in which I create a cool, complex function that sorts numbers and strings.
Thank you for reading, let’s get applause 👏 and see you next time!