🚨 JavaScript Gotcha: When 0 Actually Matters One of the most subtle bugs in JavaScript comes from using the logical OR (||) for default values. const timeout = userTimeout || 3000; Looks fine… until userTimeout = 0. 👉 JavaScript treats 0 as falsy, so instead of respecting your value, it silently replaces it with 3000. 💥 Result? Unexpected behavior. ✅ The Fix: Use Nullish Coalescing (??) const timeout = userTimeout ?? 3000; This only falls back when the value is null or undefined — not when it’s 0. 💡 When does 0 actually matter? ⏱️ Timeouts & delays → 0 can mean run immediately 📊 Counters & stats → 0 is a valid value, not “missing” 💰 Pricing / discounts → Free (0) ≠ undefined 🎚️ Sliders / configs → Minimum values often start at 0 🧠 Rule of thumb: Use || when you want to catch all falsy values (0, "", false, etc.) Use ?? when you only want to catch missing values (null, undefined) ⚡ Small operator. Big difference. Cleaner logic. #reactjs,#nodejs #JavaScript #WebDevelopment #CleanCode #Frontend #ProgrammingTips #DevTips #CodeQuality #SoftwareEngineering
JavaScript Gotcha: 0 vs Nullish Coalescing
More Relevant Posts
-
Most people don’t understand the JavaScript Event Loop. So let me explain it in the simplest way possible: JavaScript is single-threaded. It can only do ONE thing at a time. It uses something called a call stack → basically a queue of things to execute. Now here’s where it gets interesting: When async code appears (like promises or setTimeout), JavaScript does NOT execute it right away. It sends it away to the Event Loop and then keeps running what’s in the call stack. Only when the call stack is EMPTY… the Event Loop starts pushing async tasks back to be executed. Now look at the code in the image. What do you think runs first? Actual output: A D C B Why? Because not all async is equal: Promises (microtasks) → HIGH priority setTimeout (macrotasks) → LOW priority So the Event Loop basically says: “Call stack is empty? cool… let me run all promises first… then I handle setTimeout” If you get this, async JavaScript stops feeling random. #javascript #webdevelopment #frontend #reactjs #softwareengineering
To view or add a comment, sign in
-
-
🔍 JavaScript Bug You Might Have Seen (typeof null === "object") You write this: console.log(typeof null); // ? What do you expect? 👉 "null" But you get: 👉 "object" 🤯 Wait… null is NOT an object… So why is JavaScript saying this? This happens because of a historical bug in JavaScript 📌 What’s going on? In the early days of JavaScript: 👉 Values were stored in a low-level format 👉 Objects were identified by a specific type tag Unfortunately… 👉 null was given the same tag as objects So: typeof null === "object" 📌 Important point: 👉 This is NOT correct behavior 👉 But it was never fixed (for backward compatibility) 📌 So how do you check for null? ❌ Don’t do this: typeof value === "null" ✔ Do this instead: value === null 💡 Takeaway: ✔ typeof null returns "object" (bug) ✔ It’s a legacy behavior in JavaScript ✔ Always check null using === null 👉 Not everything in JavaScript makes sense… some things just stayed for history 😄 🔁 Save this before it confuses you again 💬 Comment “null” if this surprised you ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🔍 JavaScript Bug You Might Have Seen (typeof null === "object") You write this: console.log(typeof null); // ? What do you expect? 👉 "null" But you get: 👉 "object" 🤯 Wait… null is NOT an object… So why is JavaScript saying this? This happens because of a historical bug in JavaScript 📌 What’s going on? In the early days of JavaScript: 👉 Values were stored in a low-level format 👉 Objects were identified by a specific type tag Unfortunately… 👉 null was given the same tag as objects So: typeof null === "object" 📌 Important point: 👉 This is NOT correct behavior 👉 But it was never fixed (for backward compatibility) 📌 So how do you check for null? ❌ Don’t do this: typeof value === "null" ✔ Do this instead: value === null 💡 Takeaway: ✔ typeof null returns "object" (bug) ✔ It’s a legacy behavior in JavaScript ✔ Always check null using === null 👉 Not everything in JavaScript makes sense… some things just stayed for history 😄 🔁 Save this before it confuses you again 💬 Comment “null” if this surprised you ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🚀 Why Does null Show as an Object in JavaScript? 🤯 While practicing JavaScript, I came across something interesting: let myVar = null; console.log(typeof myVar); // Output: object At first, it feels confusing… why is null an object? 🤔 💡 Here’s the simple explanation: null is actually a primitive value that represents "no value" or "empty". But when JavaScript was first created, there was a bug in the typeof operator. Due to this bug, typeof null returns "object" instead of "null". ⚠️ This behavior has been kept for backward compatibility, so changing it now would break existing code. 🔍 Key Takeaways: null → means "nothing" (intentional empty value) typeof null → returns "object" (this is a historical bug) Objects (like {}) also return "object" 💻 Example: let myObj = { name: "John" }; console.log(typeof null); // object ❌ (bug) console.log(typeof myObj); // object ✅ (correct) 📌 Conclusion: Even though both return "object", they are completely different in meaning. 👉 JavaScript is powerful, but it has some quirky behaviors—this is one of them! #JavaScript #WebDevelopment #CodingJourney #100DaysOfCode #FrontendDevelopment
To view or add a comment, sign in
-
-
🚨 Ever wondered why your JavaScript code doesn’t freeze even when tasks take time? Here’s the secret: the event loop — the silent hero behind JavaScript’s non-blocking magic. JavaScript is single-threaded, but thanks to the event loop, it can handle multiple operations like a pro. Here’s the simplified flow: ➡️ The Call Stack executes functions (one at a time, LIFO) ➡️ Web APIs handle async tasks like timers, fetch, and DOM events ➡️ Completed tasks move to the Callback Queue (FIFO) ➡️ The Event Loop constantly checks and pushes callbacks back to the stack when it’s free 💡 Result? Smooth UI, responsive apps, and efficient async behavior — all without true multithreading. Understanding this isn’t just theory — it’s the difference between writing code that works and code that scales. 🔥 If you’re working with async JavaScript (Promises, async/await, APIs), mastering the event loop is a game-changer. #JavaScript #WebDevelopment #AsyncProgramming #EventLoop #Frontend #CodingTips
To view or add a comment, sign in
-
-
Can you explain the JavaScript event loop? Not because the concept is hard, but because explaining it clearly is what actually matters. Here’s the simplest way to break it down: JavaScript runs in a single thread, using a call stack to execute code. 1. Synchronous code runs first → Functions are pushed to the call stack and executed immediately 2. Async tasks are handled by the browser/environment → e.g. setTimeout, fetch, DOM events 3. Once the call stack is empty → the event loop starts working It processes queues in this order: 👉 Microtasks first (Promises, queueMicrotask) 👉 Then macrotasks (setTimeout, setInterval, I/O) Why? - A and D are synchronous → executed first - Promise (C) → microtask queue → runs next - setTimeout (B) → macrotask → runs last Explaining it step by step is simple — but doing it clearly makes all the difference. #Frontend #JavaScript #WebDevelopment #TechInterviews #SoftwareEngineering
To view or add a comment, sign in
-
-
updated solution based on feedback by Yevhen Serbyniuk how "this" works in JavaScript. the confusion: this is not consistent. it changes depending on how your function is called. arrow functions work differently than regular functions. callbacks lose context. it's a mess. why it matters: this is everywhere in JavaScript. event handlers, callbacks, class methods. if you don't understand it, you're debugging ghosts. the real issue: regular functions get this from their caller (dynamic binding). arrow functions capture this lexically from where they're defined (static binding). this fundamental difference breaks code constantly. when it breaks hardest: callbacks inside methods. event listeners in classes. promises with then(). async operations. all the places where context gets lost or wrong. the solution: understand what this should be in your context. use arrow functions if you want parent's this. use regular functions with bind() if you want explicit control. the rule: regular functions = this from caller. arrow functions = this from definition scope. know which you need. #javascript #typescript #webdevelopment #buildinpublic #reactjs
To view or add a comment, sign in
-
-
What will happen if you call a variable before initialization? 🤔 That is called Hoisting 👉 "JavaScript moves declarations to the top of their scope before execution" Sounds confusing? Let’s break it down 👇 When you create variables or functions, JavaScript runs your code in 2 phases: 1️⃣ Memory Creation Phase Before execution, JavaScript scans your code and allocates memory Example (mentally): var a → undefined let b → uninitialized (Temporal Dead Zone) 2️⃣ Execution Phase Now JavaScript runs your code line by line 👉 If you access variables before initialization: var → returns undefined let / const → ReferenceError Why does this happen? Because: var is initialized with undefined in memory let and const are hoisted but stay in the Temporal Dead Zone (TDZ) until the line where they are declared Simple way to remember: var => “exist, but don’t have a value yet” let / const => “Don’t touch before declaration” ⚡ Bonus: Function declarations are fully hoisted, so you can call them before defining them Curious how functions behave in hoisting? 🤔 Go Google function vs function expression in JavaScript — it’ll surprise you 👀 That’s hoisting in JavaScript 🚀 #javascript #webdevelopment #coding #frontend #learninpublic #hoisting
To view or add a comment, sign in
-
-
⚡ Day 7 — JavaScript Event Loop (Explained Simply) Ever wondered how JavaScript handles async tasks while being single-threaded? 🤔 That’s where the Event Loop comes in. --- 🧠 What is the Event Loop? 👉 The Event Loop manages execution of code, async tasks, and callbacks. --- 🔄 How it works: 1. Call Stack → Executes synchronous code 2. Web APIs → Handle async tasks (setTimeout, fetch, etc.) 3. Callback Queue / Microtask Queue → Stores callbacks 4. Event Loop → Moves tasks to the stack when it’s empty --- 🔍 Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); --- 📌 Output: Start End Promise Timeout --- 🧠 Why? 👉 Microtasks (Promises) run before macrotasks (setTimeout) --- 🔥 One-line takeaway: 👉 “Event Loop decides what runs next in async JavaScript.” --- If you're learning async JS, understanding this will change how you debug forever. #JavaScript #EventLoop #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
🎡 JavaScript Event Loop — Quick Challenge Most developers get this wrong 👀 🧪 What will be the output of this code? (Check the image 👇) 👉 Drop your answer in the comments before scrolling. ⏳ Think first... . . . ✅ Answer 1. Start 4. End 3. Promise.then (Microtask) 2. setTimeout (Macrotask) 🔍 Simple Explanation JavaScript runs code in this order: 1️⃣ First → Normal (synchronous) code 2️⃣ Then → All Promises (Microtasks) 3️⃣ Finally → setTimeout (Macrotasks) 👉 Even if setTimeout is 0, it still runs later. 🧠 Takeaway Promise.then → runs sooner setTimeout → runs later Simple rule, but super useful in real projects. 💬 What was your answer? #JavaScript #EventLoop #Frontend #WebDevelopment #CodingTips
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