JavaScript .sort() Quirk: Why [10, 2, 5] isn't [2, 5, 10]

💡 The JavaScript .sort() Surprise: Why [10, 2, 5] isn't [2, 5, 10] Ever had code that worked perfectly until the numbers got bigger? Check out this classic JavaScript quirk. 😅 In the screenshot, you'll notice: ✅ [3, 1, 4, 2].sort() results in [1, 2, 3, 4] (Perfect!) ❌ [10, 2, 5].sort() results in [10, 2, 5] (Wait... what?) The "Why" behind the weirdness: By default, JavaScript’s .sort() method converts elements into strings and compares their UTF-16 code unit values. It’s not looking at the numeric value; it’s looking at the characters. Just like "Apple" comes before "Banana," the string "10" comes before "2" because "1" comes before "2" in the dictionary. The Fix: To sort numbers correctly, you need to provide a compare function. This tells JavaScript exactly how to handle the math: let arr2 = [10, 2, 5]; // The correct way to sort numerically: arr2.sort((a, b) => a - b); console.log(arr2); // [2, 5, 10] tandard behavior is great for strings, but for data structures and algorithms (DSA), the compare function is your best friend! Have you ever been bitten by a default behavior in a programming language? Let’s hear your "favorite" bug in the comments! 👇 #JavaScript #WebDevelopment #CodingTips #Programming #SoftwareEngineering #DSA #LearningToCode

  • text

To view or add a comment, sign in

Explore content categories