DEV Community

Cover image for JavaScript Array.sort() Explained: Why [11, 2] Sorts Before [2, 6]
Meghana N
Meghana N

Posted on

JavaScript Array.sort() Explained: Why [11, 2] Sorts Before [2, 6]

I was just practicing some simple JavaScript, casually sorting an array like [2, 6, 11,...], when suddenly - [11, 2, 6,..]?! Wait, that can't be right... I stared at my screen, double-checked my code, and realized JavaScript's sort() wasn’t working how I expected. After some frantic head-scratching and a frustrated Google search, I finally understood what was happening under the hood.

Let me save you (who’s just like me and didn’t know 🙃) from that confusion. Here’s why JavaScript sorts numbers this way, and how to actually sort them correctly.

Image description

Image description

JavaScript's Array.prototype.sort() method converts elements to strings and compares them by their UTF-16 code unit values by default.

Here's why you get [11, 2, 2, 2, 6, 8]:

When sorted as strings, "11" comes before "2" because '1' has a lower Unicode value than '2'
Similarly, "6" and "8" come after "2" because '6' and '8' have higher Unicode values than '2'.

Image description

This behavior occurs because Array.prototype.sort() modifies the original array in place and returns a reference to the same (now sorted) array.

  1. arr.sort((a, b) => a - b) sorts the original array (arr) in place.
  2. It also returns a reference to the same array (arr), not a new array.
  3. So, result and arr are pointing to the same array in memory.
  4. When you log them, both show the sorted values.

Q: How to avoid modifying the original array?
A: If you want to keep the original array unchanged and get a new sorted array, you can:
1.Use the spread operator ([...arr]) to create a copy first:

Image description

2.Use Array.from(arr) or arr.slice() to clone the array:

Image description

Q: Why does sort() work this way?
A: JavaScript's sort() is designed to be efficient (modifying the original array avoids unnecessary memory usage).
But it can be unintuitive if you expect it to return a new array (like map(), filter(), etc.).

Key Takeaway:

  • arr.sort() modifies the original array and returns a reference to it.
  • If you don't want to mutate the original array, make a copy first.

Top comments (0)