💡 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
JavaScript .sort() Quirk: Why [10, 2, 5] isn't [2, 5, 10]
More Relevant Posts
-
💡 Pass by Value vs Pass by Reference in JavaScript (Simple Explanation) If you're learning JavaScript, understanding how data is passed is crucial 👇 🔹 Pass by Value (Primitives) When you assign or pass a primitive type (number, string, boolean, null, undefined, symbol, bigint), JavaScript creates a copy. let a = 10; let b = a; b = 20; console.log(a); // 10 console.log(b); // 20 👉 Changing b does NOT affect a because it's a copy. 🔹 Pass by Reference (Objects) When you work with objects, arrays, functions or date objects, JavaScript passes a reference (memory address). let obj1 = { name: "Ali" }; let obj2 = obj1; obj2.name = "Ahmed"; console.log(obj1.name); // Ahmed console.log(obj2.name); // Ahmed 👉 Changing obj2 ALSO affects obj1 because both point to the same object. 🔥 Key Takeaway Primitives → 📦 Copy (Independent) Objects → 🔗 Reference (Shared) 💭 Pro Tip To avoid accidental changes in objects, use: Spread operator {...obj} Object.assign() Understanding this concept can save you from hidden bugs in real-world applications 🚀 #JavaScript #WebDevelopment #Frontend #Programming #CodingTips
To view or add a comment, sign in
-
🚀 **JavaScript: var vs let vs const (Every Developer Should Know This)** Understanding the difference between `var`, `let`, and `const` is one of the most important fundamentals in JavaScript. Let’s simplify it 👇 --- 🔴 **var** • Function scoped • Can be **reassigned** • Can be **redeclared** • Hoisted and initialized as `undefined` ```javascript var x = 10; x = 20; // ✅ allowed var x = 30; // ✅ allowed ``` ⚠️ Old JavaScript way. Avoid using `var` in modern code. --- 🟢 **let** • Block scoped `{ }` • Can be **reassigned** • ❌ Cannot be redeclared in the same scope • Hoisted but in **Temporal Dead Zone (TDZ)** ```javascript let y = 10; y = 20; // ✅ allowed let y = 30; // ❌ Error ``` ✔ Best for variables that will change. --- 🟣 **const** • Block scoped • ❌ Cannot be reassigned • ❌ Cannot be redeclared • Hoisted with **Temporal Dead Zone** ```javascript const z = 10; z = 20; // ❌ Error ``` ✔ Best for constants. --- 🎯 **Best Practice** ✔ Use **const by default** ✔ Use **let when value changes** ❌ Avoid **var** This makes your code **cleaner, safer, and predictable.** --- 💬 Interview Question: What is **Temporal Dead Zone (TDZ)** in JavaScript? Comment your answer 👇 --- #JavaScript #WebDevelopment #FrontendDevelopment #Coding #Programming #SoftwareEngineering #LearnToCode #DeveloperTips #JS #TechCommunity
To view or add a comment, sign in
-
-
But I can still change const even though it is immutable, Const a = [] a.push(7) Above code is completely valid. Can anyone explain that .. comment below 👇
Immediate Joiner - Software Developer | Full Stack Web Developer | NODE JS | REACT JS | PHP | JS | GITHUB | PYTHON | DJANGO | REST API | MYSQL | MONGO DB | FLASK | WORDPRESS
🚀 **JavaScript: var vs let vs const (Every Developer Should Know This)** Understanding the difference between `var`, `let`, and `const` is one of the most important fundamentals in JavaScript. Let’s simplify it 👇 --- 🔴 **var** • Function scoped • Can be **reassigned** • Can be **redeclared** • Hoisted and initialized as `undefined` ```javascript var x = 10; x = 20; // ✅ allowed var x = 30; // ✅ allowed ``` ⚠️ Old JavaScript way. Avoid using `var` in modern code. --- 🟢 **let** • Block scoped `{ }` • Can be **reassigned** • ❌ Cannot be redeclared in the same scope • Hoisted but in **Temporal Dead Zone (TDZ)** ```javascript let y = 10; y = 20; // ✅ allowed let y = 30; // ❌ Error ``` ✔ Best for variables that will change. --- 🟣 **const** • Block scoped • ❌ Cannot be reassigned • ❌ Cannot be redeclared • Hoisted with **Temporal Dead Zone** ```javascript const z = 10; z = 20; // ❌ Error ``` ✔ Best for constants. --- 🎯 **Best Practice** ✔ Use **const by default** ✔ Use **let when value changes** ❌ Avoid **var** This makes your code **cleaner, safer, and predictable.** --- 💬 Interview Question: What is **Temporal Dead Zone (TDZ)** in JavaScript? Comment your answer 👇 --- #JavaScript #WebDevelopment #FrontendDevelopment #Coding #Programming #SoftwareEngineering #LearnToCode #DeveloperTips #JS #TechCommunity
To view or add a comment, sign in
-
-
JavaScript type coercion isn't magic. It's a spec. Every unexpected output follows the same rules, in the same order: 1. Identify the operator 2. If an object is involved → call valueOf(), then toString() 3. If operator is + and either side is a string → concatenate 4. If operator is -, *, / → convert both sides to numbers 5. Compute That's it. Five steps. Runs every time. --- Where this breaks production code: [10] + [1] = "101" → Arrays are objects. valueOf() returns the array itself (not a primitive), so toString() runs next. [10].toString() = "10", [1].toString() = "1". Then + sees two strings. Concatenates. [10] - [1] = 9 → - forces ToNumber. [10] → 10, [1] → 1. Subtracts normally. Boolean([]) = true → [] is not in the falsy list. Truthy. "0" == false → true, but Boolean("0") → true → == coerces both sides to number first. Boolean() checks the falsy list directly. input.value, localStorage, URLSearchParams → Always strings. Wrap with Number() or parseInt() before any arithmetic. --- The complete falsy list (memorise this, not the edge cases): false / 0 / -0 / 0n / "" / null / undefined / NaN Eight values. Everything else is truthy. --- Use === by default. Use == only when you explicitly want coercion — and you almost never do. The spec is 20 years old. The bugs are still new because developers skip the fundamentals. #JavaScript #WebDev #Frontend #SoftwareEngineering #Programming
To view or add a comment, sign in
-
-
JavaScript just got way more powerful (and cleaner) with this feature… Most developers still write strings like this: "Hello " + name + " you are " + age + " years old" Messy Hard to read Error-prone But there’s a better way: Template Literals (ES6) Now you can write: Hello ${name}, you are ${age} years old Clean. Simple. Powerful. Here’s why Template Literals are a game changer: String Interpolation No more + operator chaos Directly embed variables inside strings Multi-line Strings Write clean formatted text without \n Embed Expressions ${num1 + num2} ${isAdmin ? "Admin" : "Guest"} Function Calls inside Strings ${greet()} Advanced Level (Most developers don’t use this enough): Tagged Template Literals Customize how strings are processed String.raw Handle raw strings like file paths easily Real Talk: Template literals don’t just improve code They improve how you think while writing code Cleaner syntax = Better readability = Fewer bugs My Take: If you're still not using template literals properly you're writing JavaScript the hard way Pro Tip: Use template literals for: Dynamic UI content API responses Clean logging HTML rendering I recently explored this deeply and it changed how I write strings in JavaScript What about you? Are you using template literals daily or still using + ? Here is link to visit my blog: https://lnkd.in/dYiNa-bz Piyush Garg | Hitesh Choudhary | Anirudh Patel | Suraj Kameshvar Prasad #javascript #webdevelopment #coding #programming #frontend #developers #learninpublic
To view or add a comment, sign in
-
-
✍️ One syntax change. Massive readability improvement. I wrote a complete guide on Template Literals in JavaScript — and why every developer should stop using + for string building. What's covered: → The exact problems with traditional string concatenation → How backtick strings work and what ${} actually does → Embedding variables, expressions, ternaries, and function calls inline → Multi-line strings — write HTML, SQL, and logs the way they're meant to look → Real use cases: dynamic URLs, HTML generation, dynamic class names, logging → Tagged template literals — how styled-components and GraphQL's gql work under the hood Readability is not a nice-to-have. It's how you write code other people (and future you) can actually maintain. Read the full blog here 👇 🔗https://lnkd.in/gJJp2xut Check out my Hashnode profile 👇 🔗 https://lnkd.in/gAwxuryw #JavaScript #WebDevelopment #CleanCode #Programming #ES6 #piyushgarg #chaicode #hiteshchoudhary
To view or add a comment, sign in
-
-
Hot take: var isn't just outdated — it was always broken. We just didn't have anything better. I wrote a deep-dive blog post explaining exactly why modern JavaScript dropped it: 1. No block scope — variables leak outside { } blocks 2. Attaches to the global window object 3. Silent hoisting — returns undefined before declaration with zero warnings 4. Can't shadow let/const across scope boundaries 5. Forces you to write closure workarounds that let fixes in one character The post also covers the Temporal Dead Zone, the classic setTimeout loop bug, and a real code example from a closure deep-dive. If you've ever been told "just don't use var" but never understood why — this one's for you. #JavaScript #ES6 #WebDevelopment #Frontend #Programming #TechBlog
To view or add a comment, sign in
-
🔁 Understanding Loops in JavaScript — A Quick Guide Loops are fundamental in JavaScript when you need to execute a block of code multiple times. Choosing the right loop can make your code more readable and efficient. Here are the most common types of loops in JavaScript 👇 1️⃣ "for" Loop – Best when you know how many times the loop should run. for (let i = 0; i < 5; i++) { console.log("Iteration:", i); } 2️⃣ "while" Loop – Runs as long as the condition remains true. let i = 0; while (i < 5) { console.log("Count:", i); i++; } 3️⃣ "do...while" Loop – Executes at least once before checking the condition. let i = 0; do { console.log("Value:", i); i++; } while (i < 5); 4️⃣ "for...of" Loop – Perfect for iterating over iterable objects like arrays, strings, or maps. const fruits = ["Apple", "Banana", "Mango"]; for (const fruit of fruits) { console.log(fruit); } 5️⃣ "for...in" Loop – Used to iterate over object keys. const user = { name: "Sujit", role: "Frontend Developer" }; for (let key in user) { console.log(key, user[key]); } 💡 Quick Tip: Use "for...of" for arrays and "for...in" for objects to keep your code clean and readable. Mastering loops helps you handle data structures, API responses, and complex logic more efficiently. #javascript #webdevelopment #frontend #codingtips #programming
To view or add a comment, sign in
-
-
🔁 Understanding Loops in JavaScript — A Quick Guide Loops are fundamental in JavaScript when you need to execute a block of code multiple times. Choosing the right loop can make your code more readable and efficient. Here are the most common types of loops in JavaScript 👇 1️⃣ "for" Loop – Best when you know how many times the loop should run. for (let i = 0; i < 5; i++) { console.log("Iteration:", i); } 2️⃣ "while" Loop – Runs as long as the condition remains true. let i = 0; while (i < 5) { console.log("Count:", i); i++; } 3️⃣ "do...while" Loop – Executes at least once before checking the condition. let i = 0; do { console.log("Value:", i); i++; } while (i < 5); 4️⃣ "for...of" Loop – Perfect for iterating over iterable objects like arrays, strings, or maps. const fruits = ["Apple", "Banana", "Mango"]; for (const fruit of fruits) { console.log(fruit); } 5️⃣ "for...in" Loop – Used to iterate over object keys. const user = { name: "Sujit", role: "Frontend Developer" }; for (let key in user) { console.log(key, user[key]); } 💡 Quick Tip: Use "for...of" for arrays and "for...in" for objects to keep your code clean and readable. Mastering loops helps you handle data structures, API responses, and complex logic more efficiently. #javascript #webdevelopment #frontend #codingtips #programming
To view or add a comment, sign in
-
I just added a new article to my series on functional programming for the web. It's actually a new variation on a previous article, but using lazy evaluation as allowed by JavaScript through iterators, and it shows some possibilities that will help in many other cases.
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development