null and undefined
Two special values for the absence of a value.
Syntax
let x; // undefined
let y = null; // nullJavaScript 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
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.
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.
const user = { name: "Alice" };
console.log(user.email); // undefined – property not set
console.log(user.email ?? "N/A"); // "N/A" via nullish coalescingStrict equality to tell them apart
Shows that null and undefined are loosely equal but strictly different, with different typeof results.
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