Lesson 10: Mastering JavaScript Null and Undefined with challenges!

manoj ymkmanoj ymk
4 min read

🔍 null vs undefined – Deep Dive

✅ Quick Overview Table

Featurenullundefined
Typeobject (bug!)undefined
IntentIntentional absenceValue not yet assigned
Default by JS?NoYes (automatically by JS engine)
Common UseEmpty, cleared, or missing valueUninitialized variable or missing function return
Should use manually?✅ Yes⚠️ Avoid (usually default only)

1️⃣ undefined – Value Not Assigned

✅ When does undefined happen?

  • Variable declared but not initialized:

      let x;
      console.log(x); // undefined
    
  • Function without return:

      function greet() {}
      let result = greet(); 
      console.log(result); // undefined
    
  • Missing function argument:

      function sayHi(name) {
        console.log(name);
      }
      sayHi(); // undefined
    
  • Accessing nonexistent object property:

      let user = {};
      console.log(user.age); // undefined
    
  • Array holes:

      let arr = [1,,3];
      console.log(arr[1]); // undefined
    

✅ Explicitly assigning undefined:

let x = undefined; // ⚠️ Legal, but discouraged

🔸 Why discouraged? It’s hard to distinguish if the value was never set or was set to undefined manually. Use null for that instead.


2️⃣ null – Intentional Absence

✅ Use it when:

  • You want to explicitly say: “No value here.”

  • Reset a variable

  • Represent missing or empty object

Examples:

let userProfile = null; // user has not created profile yet
let selectedItem = null; // nothing selected yet

This is intentional emptiness, like a placeholder for something meaningful later.


3️⃣ Internal Types & Quirks

⚠️ typeof null returns 'object' 🤯

console.log(typeof null); // 'object' ← this is a bug in JS from 1995

This legacy bug is preserved for backward compatibility.

✅ Correct typeof values:

typeof undefined // 'undefined'
typeof null      // 'object' ⚠️

Use strict equality to differentiate:

null === undefined // false
null == undefined  // true (loose comparison)

4️⃣ Real-World Use Cases

ScenarioUse null or undefined?
Empty form field on purposenull
Optional config value not passedundefined (default)
Resetting API response valuenull
Missing object propundefined

5️⃣ Interview Alerts ⚠️

🔸 Q1: What’s the difference between undefined and null?

Answer:

  • undefined: variable declared but no value assigned (default by JS engine)

  • null: intentional absence of value, set by programmer


🔸 Q2: What’s the type of null?

Answer: 'object' due to legacy bug in JS. But semantically, null is a primitive and represents “nothing”.


🔸 Q3: Can we compare null and undefined?

null == undefined // true  ← loose equality allows type coercion
null === undefined // false ← strict equality, different types

🔸 Q4: When to use null vs undefined in code?

Use CaseBest Practice
Want to say "no value yet"Use null
Variable not initialized yetLet JS keep it undefined
Check optional parametersUse typeof or === undefined
API returns nothingReturn null explicitly if meaningful

6️⃣ Common Mistakes

  1. ❌ Using undefined to reset values

     user = undefined; // not ideal
     user = null; // ✅ better
    
  2. ❌ Confusing falsy with undefined

     let x;
     if (!x) { /* could be 0, false, '', null, or undefined */ }
    

    ✅ Use explicit comparison:

     if (x === undefined) { /* handle uninitialized */ }
    

7️⃣ Visual Analogy

TypeAnalogy
undefinedA mailbox without a letter
nullA mailbox with a note: "intentionally empty"

8️⃣ Bonus: void 0 vs undefined

You might see void 0 in old or minimized code. It returns undefined:

console.log(void 0); // undefined

Used to prevent someone from overwriting undefined (possible in pre-ES5).


🔚 Summary (Cheat Sheet)

QuestionAnswer
Default value when not assignedundefined
Intentional empty valuenull
Type of undefined'undefined'
Type of null'object' (bug)
null == undefinedtrue (loose equality)
null === undefinedfalse (strict equality)
Use null forManual, meaningful emptiness
Use undefined forDefault uninitialized values
0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk