Understanding JavaScript sort() with a Simple Example

Let’s look at this JavaScript code:

const values = [32, 25, 120];
const result = values.sort();
console.log(result);

✅ Output

[120, 25, 32]

At first glance, this output feels wrong, right?
Why didn’t JavaScript sort the numbers in ascending order?

Let’s understand why this happens.


How sort() Actually Works in JavaScript

By default, JavaScript’s sort() method:

Converts elements to strings and compares them lexicographically (dictionary order).

This is the key reason for the unexpected result.


Step-by-Step Explanation

Original array:

[32, 25, 120]

JavaScript internally converts numbers to strings:

["32", "25", "120"]

Now it sorts them alphabetically:

  • "120" comes before "25" → because "1" < "2"
  • "25" comes before "32" → because "2" < "3"

So the final order becomes:

["120", "25", "32"]

Converted back to numbers:

[120, 25, 32]

Important Warning

This behavior can easily cause bugs, especially when sorting numbers.

Do NOT rely on default sort() for numeric sorting.


Correct Way to Sort Numbers

To sort numbers properly, you must provide a compare function.

Ascending Order

values.sort((a, b) => a - b);
console.log(values);

✅ Output:

[25, 32, 120]

Descending Order

values.sort((a, b) => b - a);
console.log(values);

✅ Output:

[120, 32, 25]

Why Does JavaScript Work This Way?

JavaScript was originally designed to sort strings.

So:

  • Sorting names → works perfectly
  • Sorting numbers → needs extra instruction

This is why the compare function exists.


Key Takeaways

  • array.sort() sorts strings by default
  • Numbers are converted to strings internally
  • Always use a compare function for numeric sorting
  • sort() mutates the original array

Interview One-Liner

JavaScript’s sort() method sorts values as strings by default, so numeric sorting requires a custom compare function.


✨ Final Thought

This is one of the most common JavaScript interview traps.

If you understand this:

  • You avoid bugs
  • You write safer code
  • You stand out in interviews

Small detail. Big impact 🚀