In JavaScript, both null and undefined represent absence of a value, but they are not the same thing — they mean different kinds of “nothing”.
🎯 1. undefined
- It means a variable has been declared but not assigned a value.
- JavaScript automatically assigns
undefinedto uninitialized variables. - It’s the default value of:
- Uninitialized variables
- Missing function arguments
- Missing object properties
🧩 Example:
let a;
console.log(a); // undefined
function greet(name) {
console.log(name);
}
greet(); // undefined (no argument passed)
const obj = {};
console.log(obj.age); // undefined (property not found)
🧠 In short: undefined = “not yet assigned.”
🎯 2. null
- It means intentional absence of any object value.
- You manually assign
nullto indicate “no value” or “empty.”
🧩 Example:
let user = null;
console.log(user); // null
🧠 In short: null = “intentionally empty.”
⚖️ Comparison:
console.log(undefined == null); // true (loose equality)
console.log(undefined === null); // false (strict equality)
==performs type conversion, so they’re loosely equal.===checks type and value, so they’re different types:typeof undefined→"undefined"typeof null→"object"
🧭 Quick Summary
| Feature | undefined |
null |
|---|---|---|
| Type | undefined |
object |
| Set by | JavaScript | Developer |
| Meaning | Variable not assigned | Explicitly no value |
| Common causes | Missing value | Intentional empty value |
✅ Example Use Case:
let user = null; // means user intentionally has no data yet
let age; // means age hasn’t been set yet
🧩 In short:
undefined→ JavaScript’s way of saying “no value assigned yet.”null→ Developer’s way of saying “nothing here on purpose.”