What is logged?
const nums = [10, 2, 1];
nums.sort();
console.log(nums.join(','));
- 1,2,10
- 10,2,1
- 1,10,2
- 2,1,10
Ellen
What is logged?
const nums = [10, 2, 1];
nums.sort();
console.log(nums.join(','));
Ellen
JS sort() is basically doing the “alphabetical order” minigame here, not the “numbers go brrr” one. It coerces to strings and compares "10", "2", "1", so you end up logging 1,10,2.
Look — even when you pass a comparator, the trap is returning a boolean like a > b instead of a negative/zero/positive number, and you’ll get weird “works on my machine” ordering. Use arr. sort((a, b) => a-b) and it stops being haunted.
Okay so yeah, returning a > b is basically feeding sort() a coin flip because it coerces true/false to 1/0 and you never return “a comes before b” as a negative. I’ve seen it look fine in Chrome and then shuffle differently in Safari, which is a fun way to lose an afternoon.
Yep — and the extra nasty part is when a === b you still return false (0), so equal items get treated like “no swap needed” in a way that can hide instability until you change engines or data shape. It’s one of those bugs that “plays in tune” on your machine and then sounds wrong the moment you move it.
Yeah this bites people because sort wants a negative/zero/positive number, not a boolean, so a > b gets coerced to 1/0 and you end up with “equal” and “less than” collapsing into the same result. The safe habit is arr. sort((a, b) => a-b) (or localeCompare for strings) so the intent survives across engines.
Okay so the extra sneaky part is it can look “fine” on small arrays and then go weird once the engine’s sort hits different code paths, because returning 0 a bunch makes it basically free to keep whatever order it had. I’ve shipped the a > b version before and it only blew up when we got duplicate-ish values and suddenly the UI list started “shuffling” between renders.
JS Quiz answer: Option 3 (C).
Correct choice: 1,10,2
Why:
Without a comparator, sort converts values to strings and compares lexicographically.
Go deeper:
https://www.kirupa.com/html5/ai/strings_in_js_temp.md
Ellen ![]()
:: Copyright KIRUPA 2024 //--