🧩 What's the Deal with null and undefined?

In JavaScript, we have two ways to say “nothing” — but they’re not the same.

Both null and undefined represent absence, but they serve very different purposes:


🔍 The Quick Difference

Feature undefined null
Type undefined object (legacy quirk)
Set by JavaScript (engine) Developer (manually)
Meaning "Not assigned yet" "Intentionally empty"
Use Case Missing, uninitialized values Explicitly no value

🚀 Common Use Cases

✅ When to Use undefined:

  1. Uninitialized variables
let a;
   console.log(a); // undefined
  1. Missing function arguments
function greet(name) {
     console.log(name);
   }
   greet(); // undefined
  1. Non-existent object properties
const user = {};
   console.log(user.age); // undefined

✅ When to Use null:

  1. Intentional absence of a value
let selectedUser = null;
  1. Resetting a variable
input.value = null;
  1. End of a data structure
const node = { value: 5, next: null };
  1. Missing elements in DOM
const el = document.querySelector('.missing'); // null

🔥 Why Does null Even Matter?

Let’s say you’re sending user data:

// Using undefined
{ "middleName": undefined }  // gets stripped out in JSON.stringify

// Using null
{ "middleName": null }       // preserved: "middleName": null

null = "We asked, and they don’t have a middle name."

undefined = "We don’t even know if they have one."

This difference matters in:

  • API contracts
  • Database schemas
  • Validation logic
  • Conditional rendering

🤯 Gotchas and Fun Facts

  • null == undefinedtrue (loose equality)
  • null === undefinedfalse (strict equality)
  • typeof null'object' (weird, but true)

💡 TL;DR: When to Use What?

Situation Use
Unset variable undefined
Optional function argument undefined
Clearing a value null
End of a data structure null
API says "no value" explicitly null

💬 Interview-Ready Quote:

"undefined is what JavaScript gives you.

null is what you give JavaScript."