Skip to content
blog
2 min read

Null and Undefined

Understand the difference between null and undefined in JavaScript — two distinct primitives that both represent the absence of a value.

Both null and undefined mean “no value”, but they come from different places.

undefined

undefined is what JavaScript assigns automatically when a value is missing:

let name;
console.log(name); // undefined — declared but not assigned
function greet(name) {
console.log(name);
}
greet(); // undefined — argument not passed
const obj = {};
console.log(obj.missing); // undefined — property doesn't exist

You didn’t do anything. JavaScript did.

null

null is something you assign intentionally to say “this is empty on purpose”:

let user = null; // no user logged in yet

It’s a signal to other code that the absence is deliberate, not an oversight.

Checking for Both

null and undefined are equal with == but not ===:

null == undefined; // true
null === undefined; // false

To catch both at once, the loose equality check is useful:

if (value == null) {
// value is null OR undefined
}

typeof Quirk

typeof null returns 'object' — a known bug in JavaScript that can never be fixed for backwards compatibility:

typeof null; // 'object' — wrong, historical bug
typeof undefined; // 'undefined' — correct

Don’t rely on typeof to distinguish null from objects. Use === null instead.

Rule of Thumb

  • undefined: JavaScript is telling you something is missing
  • null: you are telling your code something is intentionally empty