arrow_back
Back

JavaScript null and undefined: empty values explained

Andrew Dorokhov Andrew Dorokhov schedule 2 min read
menu_book Table of Contents

JavaScript has two special values that both mean “empty”, but with slightly different meaning: undefined and null.

JavaScript uses undefined when it cannot find another value — for example, a newly created variable that was never assigned with =.

null is usually used to explicitly mark “there is nothing here”.

You will get undefined often without assigning it yourself. Prefer null when you intentionally want to say a variable is empty.

null

The null keyword marks the intentional absence of a value. typeof null returns "object" (a historical quirk), but in practice null is treated as its own empty value and can signal “no number / no string / no object”.

undefined

undefined means there is no value at all. It is returned when:

  • reading a variable that was never assigned;
  • reading a missing object property or array element;
  • a function has no return value;
  • a function parameter was not passed an argument.

undefined is the name of a predefined global variable (not a keyword like null) initialized to the value undefined.

Summary

Despite the differences, both values signal absence and are often interchangeable. The equality operator == treats them as equal; use === when you need to tell them apart. Both are falsy in a boolean context. Neither has properties or methods.

Treat undefined as an unexpected or erroneous absence of a value, and null as a normal, expected absence. If you need to assign one of these to a variable or pass it to a function, prefer null.

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward