✅ Understanding undefined vs null Clearly This morning’s code was: let x; console.log(x); console.log(typeof x); x = null; console.log(x); console.log(typeof x); 💡 Correct Output undefined undefined null object Yes , the last line surprises many 😄 Let’s understand why. 🧠 Simple Explanation : 🔹 Line 1: console.log(x); let x; x is declared But no value is assigned So JavaScript automatically gives it: undefined ✔ Output: undefined 🔹 Line 2: console.log(typeof x); The type of undefined is: "undefined" ✔ Output: undefined 🔹 Line 3: x = null; Here, we explicitly assign null. Important rule 👇 👉 null means intentional absence of value So: console.log(x); ✔ Output: null 🔹 Line 4: console.log(typeof x); This is the classic JavaScript quirk 👀 Even though x is null: typeof null returns: "object" ✔ Output: object 📌 This is a known bug in JavaScript kept for backward compatibility. 🎯 Key Takeaways : undefined → variable declared, value not assigned null → value explicitly set to “nothing” typeof undefined → "undefined" typeof null → "object" ❌ (historical JS bug) 📌 That’s why many developers check null like this: x === null 💬 Your Turn Did you already know typeof null is "object"? 😄 Comment “Knew it 👍” or “Learned today 😮” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #Basics #TechWithVeera #WebDevelopment
Understanding null vs undefined in JavaScript
More Relevant Posts
-
The Truth Behind JavaScript’s Oldest “Bug” 🐞 Ever felt like JavaScript was gaslighting you? 😅 typeof null === "object" has confused developers for decades. It’s often called a 30-year-old bug—but technically, it’s a legacy behavior preserved for backward compatibility. What actually happened? In the first implementation of JavaScript, values were represented as a combination of two parts, a type tag(The first 3 bits) and an actual value(with the remaining bits). The type tag for objects was 0. And null was represented as the NULL pointer which is nothing but all zeros. The JS engine saw those 3 first zeros of null and misclassified it as an object! It was a simple storage mistake. Once the web depended on it, fixing it would’ve broken the internet. So the JS team made a deliberate choice: don’t fix it. 📚 References: • MDN Web Docs: https://lnkd.in/gqAB6zJ5 • TC39 discussions: https://lnkd.in/gU3aRR3r • 2ality deep dive: https://lnkd.in/gX_qDZyz 🛡️ Safe pattern: if (data !== null && typeof data === "object") { ... } JavaScript didn’t lie to you—it just has a very long memory 😄 #JavaScript #WebDevelopment #SoftwareEngineering #ProgrammingHumor
To view or add a comment, sign in
-
-
💡 The Call Stack tracks execution. ❓ What causes a stack overflow error? The call stack is like a to-do list for JavaScript. Every time a function runs, it gets added (pushed) to the stack. When it finishes, it gets removed (popped). 👉 A stack overflow error happens when too many functions are added to the stack and it runs out of space. 🔹 Most Common Cause: Infinite Recursion function loop() { loop(); // calling itself forever } loop(); // ❌ Maximum call stack size exceeded Here, loop() keeps calling itself without stopping. Each call adds a new frame to the stack, and eventually the stack becomes full. 🔹 Proper Recursion (with base case) function countDown(n) { if (n === 0) return; // base case countDown(n - 1); } countDown(5); // ✅ works fine The base case stops the recursion and prevents overflow. ⚠️ Other Causes Deep nested function calls Large recursive algorithms without limits Circular function calls 💡 Takeaway A stack overflow happens when functions keep stacking up without finishing. Always make sure recursive functions have a clear stopping condition. #learnwithisnaan #JavaScriptTips #ModernJavaScript #ES6 #DeveloperTips #CleanCode #JSDevelopers
To view or add a comment, sign in
-
-
👯♂️ "I changed the copy, why did the original update too?!" 😱 If you’ve ever screamed this at your monitor, you’ve fallen into the Shallow Copy Trap. 🪤 In JavaScript, objects and arrays are reference types. When you copy them, it matters how you do it. 1️⃣ The Shallow Copy (The "Surface" Clone) Methods like the spread operator [...] or Object.assign() only copy the first layer of data. - If your object has nested objects inside (like user.address.city), the copy points to the same memory location as the original. - Result: You change the copy's address, and the original user's address changes too. Bugs everywhere. 🐛 2️⃣ The Deep Copy (The "True" Clone) This creates a completely independent duplicate, including all nested levels. - The Old Way: JSON.parse(JSON.stringify(obj)) (Hack, but works for simple data). - The Modern Way: structuredClone(obj) (Native, fast, and handles dates/maps correctly). 🚀 Next time you are updating state in React or manipulating complex data, ask yourself: Do I need a clone, or do I need a twin? What is your go-to method for deep cloning these days? structuredClone or Lodash? 👇 #JavaScript #WebDevelopment #CodingTips #Frontend #ReactJS #SoftwareEngineering #Programming
To view or add a comment, sign in
-
-
🌙 Evening Post — Why This if Block Always Runs This morning’s code was: let a = []; if (a) { console.log("Yes"); } else { console.log("No"); } 💡 Correct Output Yes This surprises many people 😄 Let’s understand why step by step. 🧠 Simple Explanation : 🔹 Key Rule in JavaScript 👉 In JavaScript, all objects are truthy. And: [] // is an object Even though the array is empty, it still exists in memory. So JavaScript treats it as: true 🔹 What happens in the if condition? if (a) Here: a is [] [] is truthy So the if block runs 👇 console.log("Yes"); That’s why the output is: Yes ❗ Common Mistake Beginners Make Many people think: Empty array [] → falsy ❌ Empty object {} → falsy ❌ But actually: [] → truthy ✅ {} → truthy ✅ Only these are falsy in JS: false 0 "" (empty string) null undefined NaN 🎯 Key Takeaways : Empty arrays are truthy Empty objects are truthy Truthy/falsy is about type, not size This question appears often in interviews 📌 If you want to check if an array is empty, do this instead: a.length === 0 💬 Your Turn Did you expect "Yes" or "No"? 😄 Comment “Got confused 😅” or “Clear now ✅” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #Basics #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
Ever encountered a JavaScript bug where your array mysteriously loses elements? 😳 Picture this: you're using `splice` to remove an item, but your entire array gets scrambled in production. I faced this when a `for...in` loop, meant for objects, was mistakenly used for arrays. Here's a simple example: ```javascript const arr = [1, 2, 3, 4]; for (let i in arr) { arr.splice(i, 1); } ``` In theory, you'd expect the loop to remove elements one by one. But the index shifts during each `splice`, causing skipped elements and unexpected outcomes. This little oversight can wreak havoc, especially if your array processing is complex. Why's it hard to spot? It's subtle. Your tests might pass with small data, but crash and burn with real-world inputs. Fix it by switching to a `for...of` loop or using array methods like `filter`. It ensures you process elements without altering the loop index mid-execution. This simple change made our code robust! Have you stumbled upon similar JavaScript quirks? Share your experiences! 👇 #JavaScript #Debugging #CodingProblems #JavaScript #Debugging #CodingProblems
To view or add a comment, sign in
-
Day 179: Peeling Back the JavaScript Layers 🧅 Today was all about moving beyond "how to code" and diving into how JavaScript actually works under the hood. I spent the day dissecting objects, the prototype chain, and the evolution of asynchronous patterns. 🧬 The Prototype Power I finally stopped looking at __proto__ as a mystery and started seeing it as a roadmap. Understanding how objects inherit properties from their parents—and how we can extend built-in objects with custom methods like getTrueLength()—is a total game-changer for writing dry, efficient code. ⏳ The Async Evolution: Escaping "Hell" We’ve all seen it: the pyramid of doom known as Callback Hell. Today, I practiced refactoring those nested messes into clean Promises and eventually into the sleek, readable Async/Await syntax. It's not just about making the code work; it's about making it readable for the "future me." 👯 Shallow vs. Deep Copy One of the most important lessons today was realizing that the Spread Operator (...) isn't a magic wand for copying. Shallow Copy: Quick and easy, but nested objects are still linked to the original. Deep Copy: Using JSON.parse(JSON.stringify()) to completely sever ties and create a truly independent clone. Key takeaways: Object Mastery: Using Object.values() and hasOwnProperty to navigate data safely. Array Essentials: Re-mastering map, reduce, and Array.from(). The 'New' Keyword: Understanding how it establishes that hidden link to the constructor's prototype. If you’re not understanding the prototype chain, you’re only using 50% of JavaScript’s power! #100DaysOfCode #JavaScript #WebDevelopment #CodingJourney #SoftwareEngineering #AsyncJS #Prototypes #BuildInPublic
To view or add a comment, sign in
-
🧩 JavaScript Output-Based Question (Hoisting) ❓ What will be printed? 👉 Comment your answer below (Don’t run the code ❌) Correct Output : undefined 🧠 Why this output comes? (Step-by-Step) 1️⃣ Function creates its own scope The IIFE (Immediately Invoked Function Expression) creates a new local scope. 2️⃣ var a is hoisted inside the function Inside the function, this line: var a = 20; is treated by JavaScript as: var a; // hoisted a = 20; // assigned later So when console.log(a) runs: • the local a exists • but it is not initialized yet That’s why: undefined is printed instead of 10. 3️⃣ Local a shadows the global a The global a = 10 is completely ignored inside the function because the local var a shadows it. 🔑 Key Takeaways ✔️ var declarations are hoisted ✔️ Initialization happens later ✔️ Local variables shadow global ones ✔️ Hoisting bugs often appear inside functions Hoisting doesn’t move code — it moves declarations. #JavaScript #Hoisting #InterviewQuestions #FrontendDeveloper #MERNStack #WebDevelopment
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
-
🚀 JavaScript Tip: var vs let vs const — Explained Simply Understanding how variables work in JavaScript can save you from hard-to-debug issues later. Think of variables as containers that hold values ☕ 🔹 var – Old Style (Not Recommended) ➡️ Function scoped ➡️ Can be re-declared & reassigned ➡️ Gets hoisted → may cause unexpected bugs 👉 Use only if maintaining legacy code 🔹 let – Modern & Safe ➡️ Block scoped {} ➡️ Cannot be re-declared ➡️ Can be reassigned ➡️ Hoisted but protected by Temporal Dead Zone 👉 Best for values that change over time 🔹 const – Locked & Reliable ➡️ Block scoped {} ➡️ Cannot be re-declared or reassigned ➡️ Must be initialized immediately 👉 Best for fixed values and cleaner code ✅ Best Practice Use const by default, switch to let only when reassignment is needed, and avoid var 🚫 💡 Small fundamentals like these make a big difference in writing clean, scalable JavaScript. #JavaScript #WebDevelopment #FrontendDevelopment #ProgrammingTips #LearnJavaScript #CodingBestPractices #DeveloperLearning #SoftwareEngineering #100DaysOfCode
To view or add a comment, sign in
-
-
Reversing a string in JavaScript can be done in more than one way. I revisited this problem today and tried three approaches, each with a different mindset: // 1. Using built-in methods const reverse1 = (str) => str.split("").reverse().join(""); // 2. Using a loop (more control) function reverse2(str) { let result = ""; for (let i = str.length - 1; i >= 0; i--) { result += str[i]; } return result; } // 3. Using reduce (functional style) const reverse3 = (str) => str.split("").reduce((acc, char) => char + acc, ""); console.log(reverse1("hello")); //"olleh" console.log(reverse2("hello")); //"olleh" console.log(reverse3("hello")); //"olleh" Methods I used: • Built-in methods → concise and readable • Loop → full control and clarity • reduce → functional and expressive This reminded me that in real projects, how you think about a problem matters as much as the answer itself. Still learning, still building, still showing up. #JavaScript #FrontendDevelopment #LearningInPublic #JuniorDeveloper
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
Good explanation