← JavaScript

Fundamentals

What is the difference between `null` and `undefined`?

Show answer — try answering out loud first

undefined means a variable exists but has no assigned value (JavaScript sets it). null is an absence of value that the programmer assigns on purpose.

  • undefined: the default value. It shows up when you declare a variable without giving it a value, when a function doesn't return anything, or when you access a property that doesn't exist. JavaScript assigns it automatically.
  • null: you write it intentionally to say "there's nothing here, and it's on purpose". For example, to clear a variable that previously held an object.

Both are "empty", but undefined is an accidental or default emptiness, while null is an intentional emptiness.

let sinValor;
console.log(sinValor); // undefined (declared, not assigned)

const obj = {};
console.log(obj.propiedadInexistente); // undefined

function sinRetorno() {}
console.log(sinRetorno()); // undefined

// You assign null on purpose
let usuario = { nombre: "Mike" };
usuario = null; // "there's no user anymore, on purpose"
console.log(usuario); // null

// Important comparisons
console.log(null == undefined);  // true  (coercion: they are "similar")
console.log(null === undefined); // false (different types)
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object" (historical bug)
  • Believing that null and undefined are identical. With == they seem equal, but with === they're not, and their meaning is different.
  • Being surprised that typeof null is "object". It's a historical bug in the language that's kept for backward compatibility.

"JavaScript sets undefined automatically when a variable has no value, a function doesn't return anything, or a property doesn't exist. I assign null on purpose to represent 'there's no value'. With == they are equal because of coercion, but with === they're not, because they are different types. A curious detail is that typeof null returns 'object', which is a historical bug in the language."

Quick challenge

What does this print?

console.log(null == undefined);
console.log(null === undefined);
console.log(typeof undefined === typeof null);
See answer

true, false, false. The first is true because of coercion. The second is false because the types differ. The third compares "undefined" with "object", which are different.