DEV Community

keshav Sandhu
keshav Sandhu

Posted on

null vs undefined in JavaScript: The Tale of Two Nothing

🧩 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 
Enter fullscreen mode Exit fullscreen mode
  1. Missing function arguments
 function greet(name) { console.log(name); } greet(); // undefined 
Enter fullscreen mode Exit fullscreen mode
  1. Non-existent object properties
 const user = {}; console.log(user.age); // undefined 
Enter fullscreen mode Exit fullscreen mode

✅ When to Use null:

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

🔥 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 
Enter fullscreen mode Exit fullscreen mode

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."


Top comments (0)