Compare .sort() and .toSorted() methods

ProgrammingCouple
3 min readJan 19, 2024

--

The different variables and their references comparison
The different variables and their references comparison

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();
Console of .toSorted() method result
Console of .toSorted() method result

In the next step, use the .sort() method and assign the result to another variable. Repeat the sort check.

const sortReference = ORIGINAL_DATA.sort();
Console of .sort() method result
Console of .sort() method result

At first glance, the methods work identically because the difference is visible when we compare object references.

Object reference comparison
Object reference comparison

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?

Object reference comparison
Object reference comparison

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.

What happens to the original data when we use the Sort method instead of toSorted
What happens to the original data when we use the sort method instead of toSorted

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!

--

--

ProgrammingCouple
ProgrammingCouple

Written by ProgrammingCouple

See programmingcouple.com with useful tools and statistics for Medium Members

No responses yet