JavaScript sort() Default Behavior: String Comparison

✅ Why JavaScript Sorted These Numbers WRONG (But Correctly 😄) This morning’s code was: const nums = [1, 10, 2, 21]; nums.sort(); console.log(nums); 💡 Correct Output [1, 10, 2, 21] Yes — not numerically sorted 👀 Let’s understand why. 🧠 Deep but Simple Explanation 🔹 How sort() works by default 👉 JavaScript converts elements to strings first 👉 Then sorts them lexicographically (dictionary order) So the numbers become strings internally: ["1", "10", "2", "21"] Now JS sorts them like words: "1" "10" "2" "21" Which gives: [1, 10, 2, 21] 🔹 Why this is dangerous Developers expect numeric sorting: [1, 2, 10, 21] But JavaScript does string comparison by default. That’s why this bug appears in: scores prices rankings pagination 🔹 Correct way to sort numbers nums.sort((a, b) => a - b); Now JavaScript compares numbers, not strings. 🎯 Key Takeaways : sort() mutates the original array Default sort() = string comparison Numbers must use a compare function This is one of the most common JS bugs 📌 If you remember only one thing: Never trust sort() without a comparator. 💬 Your Turn Did this ever break your code? 😄 Comment “Yes 😅” or “Learned today 🤯” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment

  • graphical user interface

To view or add a comment, sign in

Explore content categories