✅ 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
JavaScript sort() Default Behavior: String Comparison
More Relevant Posts
-
Did you know that when you use an array inside a JavaScript template literal, it doesn’t behave like an array at all? If you write something like: `Stack: ${['React', 'Node', 'TypeScript']}` you might expect JSON-style output or the array structure. But JavaScript actually produces: "Stack: React,Node,TypeScript" That’s because template literal interpolation triggers implicit coercion: .toString() → .join(',') This isn’t a quirk — it’s part of the language design, and arrays have always been stringified using commas. Where this is useful There are a few scenarios where this implicit join is convenient: 1 - quick logging or debugging 2 - passing arrays into string-based utilities 3 - small helper functions where formatting doesn’t matter, etc. Where it becomes risky In more sensitive areas — UI text, error messages, URLs, file paths, nested arrays — this implicit join can lead to subtle formatting bugs or unreadable output, especially if you didn’t intend commas. My recommendation For clarity and predictability in production code, being explicit is usually the better choice: `Technologies: ${tech.join(', ')}` Making the formatting intentional helps avoid surprises and keeps code easier to understand for everyone reading it. #JavaScript #React #WebDevelopment #FrontendEngineering
To view or add a comment, sign in
-
-
🧠 Most JavaScript devs argue over this — and that’s the point 👀 (Even seniors don’t agree immediately) No frameworks. No libraries. Just how JavaScript actually schedules work. 🧩 Output-Based Question (Event Loop: microtasks vs macrotasks) console.log("A"); setTimeout(() => { console.log("B"); }, 0); Promise.resolve().then(() => { console.log("C"); }); queueMicrotask(() => { console.log("D"); }); console.log("E"); ❓ What will be printed — in the correct order? ❌ Don’t run the code 🧠 Think like the JavaScript engine A. A → E → C → D → B B. A → C → D → E → B C. A → E → D → C → B D. A → E → C → B → D 👇 Drop ONE option only (no explanations yet 😄) Why this matters Most developers know: Promises run before setTimeout But many don’t know: queueMicrotask runs before .then Console order ≠ execution intuition One wrong assumption = flaky UI or race bugs When fundamentals aren’t clear: async bugs feel random production issues are hard to reproduce debugging becomes guesswork Strong JavaScript developers don’t memorize outputs. They understand why the engine schedules work this way. 💡 I’ll pin the full breakdown after a few answers. #JavaScript #EventLoop #AsyncJavaScript #JSFundamentals #WebDevelopment #FrontendDeveloper #FullStackDeveloper #CodingInterview #DevCommunity #VibeCode
To view or add a comment, sign in
-
-
🚀 Just published: The JavaScript Variable Declaration Trilogy After years of writing JavaScript, I decided to go beyond the usual "use const by default" advice and explore the why behind var, let, and const. In this deep dive, I cover: ✅ The Temporal Dead Zone (and why it catches bugs you didn't know you had) ✅ The closure gotcha that's bitten every JS developer at least once ✅ Why const doesn't mean immutable (and what it actually protects) ✅ Performance implications nobody talks about ✅ Real-world horror stories and how let/const solve them This isn't another surface-level comparison it's about building the right mental models to write bulletproof JavaScript. Full breakdown with visual walkthroughs 👇 https://lnkd.in/ehQs6Nbf #JavaScript #WebDevelopment #Programming #ES6 #SoftwareEngineering #CodingTips #FrontendDevelopment
To view or add a comment, sign in
-
The "All-in-One" Wand: JSX & CSS-in-JS 🧙♂️💻 Headline: Why React Devs are ditching separate CSS files. (It’s not Dark Arts!) ⚡ I’m diving deep into JSX with "Harry Sir." One thing is clear: the boundary between HTML, JS, and CSS is vanishing. 🪄 1. The "Inline Style" Hex 🪄 In JSX, styles aren't strings—they are JavaScript Objects. The Syntax: style={{ color: 'gold' }} The Logic: The outer {} is the JS gate; the inner {} is the Object. It’s a spell inside a protective charm! 🛡️ 2. The className Charm 🏰 Since class is a reserved word in JS, we use className. The Benefit: We can make classes dynamic. Example: <div className={isWinner ? 'gryffindor' : 'muggle'}> 🦁 3. HFT Simulation: Why Style in JS? 📈 Building a High-Frequency Trading dashboard? You need speed. Manual CSS: Toggling classes is slow for the DOM. 🐢 JSX Power: Style is a direct function of State. Result: color: price > lastPrice ? 'green' : 'red'. 💹 The UI reacts at the speed of data, not the browser parser! 🏎️ The Practical Takeaway: This is Encapsulation. You're building self-contained magical objects (Components) that carry their own logic and look. No more hunting through 1,000 lines of CSS! 🔍✨ Question for Devs: Are you "Old School" CSS or have you embraced "Total Transfiguration" with CSS-in-JS? 🧪 #ReactJS #JSX #CodeWithHarry #WebDev #HFT #Programming #Frontend #Btech #Nexus_Init
To view or add a comment, sign in
-
-
𝗪𝗵𝘆 𝗱𝗼𝗲𝘀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗹𝗲𝘁 𝘆𝗼𝘂 𝘂𝘀𝗲 𝘃𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀 𝗯𝗲𝗳𝗼𝗿𝗲 𝘁𝗵𝗲𝘆’𝗿𝗲 𝗱𝗲𝗰𝗹𝗮𝗿𝗲𝗱? 🤔 Hi everyone! Following up on my last post, Part 2 of my JavaScript deep-dive series is now live on Medium! Today, we’re tackling one of the most famous (and often misunderstood) behaviors in the language: 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴. If you’ve ever wondered why var gives you undefined, but let throws a ReferenceError, or why function declarations work anywhere in your file, this article is for you. 𝗜𝗻 𝗣𝗮𝗿𝘁 2, 𝗜 𝗯𝗿𝗲𝗮𝗸 𝗱𝗼𝘄𝗻: • 𝗧𝗵𝗲 𝗣𝗿𝗲𝗽𝗿𝗼𝗰𝗲𝘀𝘀𝗶𝗻𝗴 𝗦𝘁𝗲𝗽: Why the engine scans your code before running it. • 𝗧𝗵𝗲 "𝘃𝗮𝗿" 𝗠𝘆𝘀𝘁𝗲𝗿𝘆: Why declarations are hoisted, but values are not. • 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝘃𝘀. 𝗖𝗹𝗮𝘀𝘀 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴: Why they behave so differently. • 𝗧𝗵𝗲 𝗧𝗲𝗺𝗽𝗼𝗿𝗮𝗹 𝗗𝗲𝗮𝗱 𝗭𝗼𝗻𝗲 (𝗧𝗗𝗭): Demystifying the "forbidden zone" of modern JS. I also address the biggest myth in JS: 𝗗𝗼𝗲𝘀 𝘁𝗵𝗲 𝗲𝗻𝗴𝗶𝗻𝗲 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 "𝗺𝗼𝘃𝗲" 𝘆𝗼𝘂𝗿 𝗰𝗼𝗱𝗲 𝘁𝗼 𝘁𝗵𝗲 𝘁𝗼𝗽 𝗼𝗳 𝘁𝗵𝗲 𝗳𝗶𝗹𝗲? Check out the full breakdown here: https://lnkd.in/dGZJMbB4 🔗 I’d love to hear your thoughts or any "Hoisting horror stories" you've encountered in your own projects! 𝗡𝗲𝘅𝘁 𝘂𝗽: We move from how variables are registered to where they live: 𝗦𝗰𝗼𝗽𝗲 𝗮𝗻𝗱 𝘁𝗵𝗲 𝗦𝗰𝗼𝗽𝗲 𝗖𝗵𝗮𝗶𝗻. #JavaScript #WebDevelopment #Hoisting #SoftwareEngineering #TechCommunity #CodingLife #Medium
To view or add a comment, sign in
-
🚨 90% of JavaScript Developers Get This Wrong (Even with 2–4 years of experience 👀) No frameworks. No async tricks. Just pure JavaScript fundamentals. 🧠 Output-Based Question (Set + Type Checking) const s = new Set(); s.add(5); console.log(s.has('5')); ❓ What will be printed? ❌ Don’t run the code 🧠 Think like the JavaScript engine A. true B. false C. error D. undefined 👇 Drop ONE option only (no explanations yet 👀) ⚠️ Why This Question Matters Most developers assume: • JavaScript auto-converts types • '5' and 5 are basically the same • Collections behave like loose equality All three assumptions can break real applications. 🎯 What This Actually Tests • How Set stores values • Strict equality (===) behavior • Primitive type comparison • Why type consistency matters in production When this mental model is unclear: • Cache checks fail • Permission checks break • Duplicate detection becomes unreliable Strong JavaScript developers don’t rely on “automatic conversion”. They understand how values are actually stored and compared. 💡 I’ll pin the breakdown after a few answers. #JavaScript #JSFundamentals #CodingInterview #WebDevelopment #FrontendDeveloper #FullStackDeveloper #DevelopersOfLinkedIn #ProgrammingTips
To view or add a comment, sign in
-
-
This JavaScript array question surprises many developers 👀 🧩 JavaScript Output-Based Question (Array length + delete) ❓ What will be the output? 👉 Comment your answer below (Don’t run the code ❌) Correct Output : 11 Why this output comes? (Step-by-Step) 1️⃣ Initial array ['a','b','c','d','e'] Length = 5 2️⃣ Assigning value at index 10 array[10] = 'f'; • JavaScript creates empty slots between index 5–9 • Array becomes sparse • Length becomes highest index + 1 ➡️ Length = 11 3️⃣ Deleting the element delete array[10]; • delete removes the value • ❌ It does NOT reindex the array • ❌ It does NOT reduce length So the slot becomes empty, but length stays the same. ➡️ Final length = 11 🔑 Key Takeaways : ✔️ Array length depends on highest index ✔️ delete removes value, not index ✔️ delete does NOT change array length ✔️ Sparse arrays are common sources of bugs delete is usually a bad choice for arrays. #JavaScript #Arrays #InterviewQuestions #FrontendDeveloper #MERNStack #WebDevelopment
To view or add a comment, sign in
-
-
This JavaScript array question surprises many developers 👀 🧩 JavaScript Output-Based Question (Array length + delete) ❓ What will be the output? 👉 Comment your answer below (Don’t run the code ❌) Correct Output : 11 Why this output comes? (Step-by-Step) 1️⃣ Initial array ['a','b','c','d','e'] Length = 5 2️⃣ Assigning value at index 10 array[10] = 'f'; • JavaScript creates empty slots between index 5–9 • Array becomes sparse • Length becomes highest index + 1 ➡️ Length = 11 3️⃣ Deleting the element delete array[10]; • delete removes the value • ❌ It does NOT reindex the array • ❌ It does NOT reduce length So the slot becomes empty, but length stays the same. ➡️ Final length = 11 🔑 Key Takeaways : ✔️ Array length depends on highest index ✔️ delete removes value, not index ✔️ delete does NOT change array length ✔️ Sparse arrays are common sources of bugs delete is usually a bad choice for arrays. #JavaScript #Arrays #InterviewQuestions #FrontendDeveloper #MERNStack #WebDevelopment
To view or add a comment, sign in
-
-
Day 15: The this Keyword in JavaScript this is one of the most misunderstood concepts in JavaScript 🤯 Its value depends on HOW a function is called, not where it is written. 🔹 1️⃣ Global Scope console.log(this); 👉 In browser → window 👉 In Node → {} (module.exports) 🔹 2️⃣ Inside a Regular Function function show() { console.log(this); } show(); 👉 In non-strict mode → window 👉 In strict mode → undefined 🔹 3️⃣ Inside an Object Method const user = { name: "Shiv", greet: function() { console.log(this.name); } }; user.greet(); 👉 this refers to the object → user 🔹 4️⃣ Arrow Function const user = { name: "Shiv", greet: () => { console.log(this); } }; user.greet(); 👉 Arrow functions do NOT have their own this 👉 They inherit from their lexical scope 🔥 Key Rule this depends on: ✔️ How the function is called ✔️ Whether it’s arrow or regular ✔️ Strict mode 🧠 Why Important? ✔️ Core interview topic ✔️ Important in React ✔️ Needed for call, apply, bind #JavaScript #thisKeyword #Frontend #Webdevelopment #learnInPublic
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
Learned today