JavaScript null vs undefined
ā JavaScript null vs undefined Cheatsheet
null and undefined both represent empty values, but they mean different things and behave differently in logical comparisons and type checks.
ā undefined ā null ā Differences ā typeof behavior ā Checking for empty values ā Nullish coalescing
#javascript #null #undefined #types #comparison #webdev #frontend #coding #tips
JavaScript comes with two values that means "no value": undefined and null.
undefined means a variable has been declared but has not been assigned a value.
null, on the other hand, is an intentional absence of value assigned by the developer.
undefined
undefined is the default value for uninitialized variables, missing function arguments, and object properties that do not exist.
let name;
console.log(name); // undefinedfunction greet(message) {
console.log(message);
}
greet(); // undefinedconst user = {};
console.log(user.age); // undefinednull
null represents a deliberate "no value". It is often used to clear a variable or indicate that an object reference is intentionally empty.
let user = { name: "Ada" };
user = null; // intentionally cleared
console.log(user); // nullKey differences
| Aspect | undefined | null |
|---|---|---|
| Meaning | Value not assigned | Intentional absence of value |
| Type | "undefined" | "object" (legacy bug) |
| Default | Given by JavaScript | Assigned by developer |
== comparison | undefined == null is true | null == undefined is true |
=== comparison | undefined === null is false | null === undefined is false |
typeof behavior
typeof undefined; // "undefined"
typeof null; // "object" (a legacy JavaScript quirk)To check for null, use strict equality.
const value = null;
value === null; // trueChecking for empty values
Use strict equality when you need to distinguish between null and undefined.
const a = null;
const b = undefined;
a === null; // true
b === undefined; // true
a === b; // falseUse loose equality when either value should be treated as empty.
const value = null;
if (value == null) {
console.log("value is null or undefined");
}Nullish coalescing
The ?? operator treats only null and undefined as missing values.
It returns the right-hand side if the left-hand side is null or undefined, otherwise it returns the left-hand side.
const count = 0;
console.log(count ?? 10); // 0
const name = null;
console.log(name ?? "Anonymous"); // "Anonymous"Full-Stack AI Developer Roadmap
From HTML & CSS to working with AI models, all in one structured roadmap.