What is the difference between null and undefined?

undefined means a value has not been set (the language's default), while null means "intentionally empty" (a value a developer chose to assign).

Where undefined appears automatically

  • A declared variable with no value: let x;
  • A missing function argument.
  • A missing object property or array element.
  • A function with no return.

Where null appears

Only when someone sets it: user.avatar = null, or APIs that return null for "nothing found" (document.querySelector, String.prototype.match, JSON.parse("null")).

Differences that bite

  • typeof undefined is "undefined"; typeof null is "object".
  • null == undefined is true, but null === undefined is false.
  • Default parameters apply for undefined only: passing null keeps null.
  • JSON: JSON.stringify({ a: undefined, b: null }) gives {"b":null}; undefined properties are dropped.
  • Arithmetic: null + 1 is 1, undefined + 1 is NaN.

Handling both

  • value ?? fallback replaces both null and undefined (but not 0 or "").
  • obj?.prop stops safely if obj is either.
  • value == null checks for both in one expression.

Convention

Many teams use undefined for "not provided" and null for "explicitly cleared", and stay consistent.

Code example

js
1let notSet;
2const user = { name: "Ada", avatar: null };
3
4console.log(notSet); // undefined
5console.log(user.email); // undefined (missing property)
6console.log(user.avatar); // null (set on purpose)
7
8console.log(typeof undefined, typeof null); // "undefined" "object"
9console.log(null == undefined, null === undefined); // true false
10
11// Default parameters only replace undefined
12const greet = (name = "friend") => `Hi ${name}`;
13console.log(greet(undefined), greet(null)); // "Hi friend" "Hi null"
14
15// JSON drops undefined, keeps null
16console.log(JSON.stringify({ a: undefined, b: null })); // {"b":null}
17
18// Arithmetic
19console.log(null + 1, undefined + 1); // 1 NaN
20
21// Handle both with ?? and ?.
22console.log(user.avatar ?? "default.png"); // default.png
23console.log(user.settings?.theme ?? "light"); // light

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app