- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Sorting in JavaScript
Sorting
Sorting in JavaScript
You will almost never write a sorting algorithm at work. You will constantly write comparators - and getting one wrong is a bug that survives review because the output looks nearly right.
The default is wrong for numbers
The bug everyone hits once
javascript
const nums = [10, 9, 100, 1]
nums.sort()
console.log(nums) // [1, 10, 100, 9] — sorted as strings
nums.sort((a, b) => a - b)
console.log(nums) // [1, 9, 10, 100] — correct