Ever used .sort() without a callback and thought it βjust worksβ?
Wellβ¦ sometimes it does. Sometimes it doesnβt. π
Letβs look at this π
const users = [
{ name: 'Charlie', age: 28 },
{ name: 'Alice', age: 32 },
{ name: 'Bob', age: 25 },
];
// 1οΈβ£ Without callback
console.log(users.sort());
// β Unexpected β compares stringified objects, not what you want
// 2οΈβ£ With callback
console.log(users.sort((a, b) => a.name.localeCompare(b.name)));
// β
Correct β sorts alphabetically by name
π¬ Key takeaway:
sort() without a callback converts items to strings and compares their Unicode order.
To sort objects properly, always pass a comparator.
Next time you see .sort(), ask yourself β
π βIs JavaScript sorting what I think itβs sorting?β
#JavaScript #WebDevelopment #CodingTips #Frontend #TypeScript