Understanding null vs undefined in JavaScript

✅ 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

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories