Question

What is the difference between null and undefined in JavaScript?

Vault Verified
Curated Intelligence
Definitive Source
Answer

Undefined means a value was never assigned. Null means a value was deliberately set to nothing. The language draws that distinction, and whether your code should is a style decision worth making explicitly rather than by accident.

Undefined appears on its own in several situations: a declared variable before assignment, a missing function parameter, a property that does not exist on an object, an array index out of range, and the return value of a function with no return statement. You rarely write it yourself.

Null only appears when something puts it there. Your own code, or an API returning it to represent an intentionally empty field, most commonly a database column that is genuinely empty rather than absent.

The practical consequences show up in comparisons. Loose equality treats them as equal to each other but not to anything else, which is one of the few defensible uses of loose equality. Strict equality distinguishes them. A quirk worth knowing is that the type check on null reports object, a long-standing bug in the language kept for compatibility.

Default parameter values trigger for undefined but not for null, so passing null explicitly overrides a default while omitting the argument does not. This surprises people regularly.

The nullish coalescing operator exists precisely for this area. Unlike the logical or operator it only falls back for null and undefined, not for empty strings, zero or false. That difference matters whenever zero or an empty string is a legitimate value, which is a common source of subtle bugs when the older operator is used for defaults.

Many teams simply standardise on one for absence, usually undefined internally and null at API boundaries.

Related Questions