null and undefined

Two special values for the absence of a value.

Syntaxlet x; // undefined let y = null; // null

JavaScript has two values that mean "no value":

  • undefined — a variable has been declared but not given a value.
  • null — a value that intentionally represents "nothing".

Rule of thumb

Use null when you deliberately want to say "empty". Leave things undefined when you simply have not set them yet.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Represent an optional user profile photo as null when the user has not uploaded one yet.
  • Detect an undefined object property to provide a default value with the nullish coalescing operator.
  • Distinguish between a form field that was deliberately cleared (null) versus never rendered (undefined).

More examples

null as intentional absence

Assigns null to represent the deliberate absence of a value, then replaces it with a default.

Example · js
let avatar = null; // user has not uploaded a photo yet
if (avatar === null) {
  avatar = "/default-avatar.png";
}
console.log(avatar);

undefined from missing property

Accesses a missing object property that returns undefined, then uses ?? to supply a fallback.

Example · js
const user = { name: "Alice" };
console.log(user.email);           // undefined – property not set
console.log(user.email ?? "N/A");  // "N/A" via nullish coalescing

Strict equality to tell them apart

Shows that null and undefined are loosely equal but strictly different, with different typeof results.

Example · js
console.log(null == undefined);   // true  – loose equality
console.log(null === undefined);  // false – strict equality
console.log(typeof null);         // "object"
console.log(typeof undefined);    // "undefined"

Discussion

  • Be the first to comment on this lesson.