JavaScript traps · JavaScript

JavaScript can't sort numbers?!PRO

Watch the video

sort() compares as text by default, so 10 lands before 2. The a - b fix, and why sort() changes your array.

// JavaScript can't sort numbers ?! — sort() compares as TEXT by default.
const nums = [10, 1, 2, 25, 100];
console.log([...nums].sort());                  // [1, 10, 100, 2, 25] ?!
console.log([...nums].sort((a, b) => a - b));   // [1, 2, 10, 25, 100] ✓
console.log([...nums].sort((a, b) => b - a));   // biggest first ✓

// Bonus: sort() changes the original array!
const orig = [3, 1, 2];
orig.sort();
console.log(orig);   // [1, 2, 3] — the original moved ?!
Open code JS2 in Pocket Compiler Download the Pocket Compiler app — free

No app yet? Install it, then open the app and type the code JS2 in Code Library.