null and undefined in JavaScript: Differences, Checks and Best Practices
Why JavaScript has two "no value" values, every place undefined appears automatically, how null and undefined differ in typeof, equality, arithmetic, JSON and default parameters, how to check for them safely with ?? and ?., and which one your own code should use.
kvi5hnuCode Sprout team member7 min readOn this page
Most languages have one value meaning "nothing": null in Java and C#, None in Python, nil in Ruby and Go. JavaScript has two: undefined and null. They're similar enough to be confusing and different enough to cause bugs. This article shows exactly where each comes from, how they behave, and a simple convention for using them.
The short version
undefinedmeans "no value has been assigned". The language produces it automatically.nullmeans "deliberately empty". JavaScript itself almost never produces it; programmers (and APIs) assign it on purpose.
Each is the only value of its own type, and both are falsy.

Where undefined comes from
You rarely write undefined yourself. The language hands it to you in all of these situations:
let notAssigned;
const settings = { theme: "dark" };
function greet(name) { return name; }
function doNothing() {}
const list = [10, 20];
console.log(notAssigned); // a declared variable without a value
console.log(settings.fontSize); // a property that doesn't exist
console.log(greet()); // a parameter with no argument passed
console.log(doNothing()); // a function that doesn't return a value
console.log(list[5]); // an array index past the end
console.log(void 0); // the void operator always gives undefined
undefined
undefined
undefined
undefined
undefined
undefined
And null? DOM methods return it when nothing is found (document.querySelector(".missing")), JSON.parse("null") produces it, regex match returns it for no match, and Object.getPrototypeOf(Object.prototype) is null, the end of every prototype chain. Elsewhere, null appears only because someone wrote it.
How they differ
console.log(typeof undefined, typeof null); // the famous typeof quirk
console.log(null == undefined, null === undefined);
console.log(Number(undefined), Number(null)); // NaN vs 0
console.log(undefined + 1, null + 1);
console.log(JSON.stringify({ a: undefined, b: null }));
console.log(JSON.stringify([undefined, null]));
undefined object
true false
NaN 0
NaN 1
{"b":null}
[null,null]
undefined | null | |
|---|---|---|
| Meaning | not assigned yet / missing | intentionally empty |
| Produced by | the language, automatically | programmers and some APIs |
typeof | "undefined" | "object" (a historical bug) |
| As a number | NaN | 0 |
In JSON.stringify | property omitted; null in arrays | kept as null |
| Triggers default parameters and destructuring defaults | yes | no |
| Is a keyword | no: a read-only global property | yes: a literal |
The arithmetic row matters in practice: a missing value that's null silently becomes 0 in a sum, while undefined turns the sum into NaN.
Defaults only replace undefined
Default parameter values and destructuring defaults kick in only for undefined. Passing null means "I'm deliberately passing nothing", so the default is not used:
function setVolume(level = 50) {
return level;
}
console.log(setVolume(), setVolume(undefined), setVolume(null), setVolume(0));
const { width = 100, height = 100 } = { width: null, height: undefined };
console.log(width, height);
50 50 null 0
null 100
This is a common surprise with APIs that return null for missing fields: your destructuring defaults won't apply. Use ?? to cover both.
Accessing properties on null or undefined throws
Primitives like strings and numbers have methods (through wrapper objects, article 9), but null and undefined have no properties at all. Reading any property throws a TypeError, the most common runtime error in JavaScript:
const response = { user: null };
try {
console.log(response.user.name);
} catch (err) {
console.log(err.name);
}
console.log(response.user?.name); // optional chaining: no error
console.log(response.profile?.avatar?.url); // stops at the first null/undefined
console.log(response.user?.name ?? "Guest"); // with a fallback
TypeError
undefined
undefined
Guest
In Chrome and Node.js the message reads Cannot read properties of null (reading 'name'), which names the property you tried to read; the value before the dot was null. Firefox phrases it as response.user is null.
The optional chaining operator ?. (ES2020) short-circuits: if the value on its left is null or undefined, the whole chain evaluates to undefined instead of throwing. It also works for calls (callback?.()) and brackets (row?.[0]). Use it where a missing value is expected. Where it isn't, letting the error happen is better than hiding a bug.
Checking for null and undefined
| To check | Write | Notes |
|---|---|---|
null or undefined | x == null | the one widely accepted use of == |
exactly undefined | x === undefined | |
exactly null | x === null | |
| a variable that may not be declared | typeof x === "undefined" | never throws |
| fallback value | x ?? fallback | only for null/undefined, unlike || |
| assign a default in place | x ??= fallback | ES2021 |
const config = { retries: 0, label: "", timeout: null };
console.log(config.retries || 3, config.retries ?? 3); // 0 is valid data
console.log(config.label || "none", config.label ?? "none");
console.log(config.timeout ?? 5000);
config.timeout ??= 5000; // assign only if null or undefined
config.retries ??= 3; // 0 stays 0
console.log(config);
3 0
none
5000
{ retries: 0, label: '', timeout: 5000 }
x == null is true for exactly two values, null and undefined, and nothing else (not 0, "" or false). Many style guides, and ESLint's eqeqeq rule with its "null": "ignore" option, allow this one use of ==.
Missing vs present-but-undefined
A property can exist and hold undefined. Reading it can't tell the difference from a missing property; use in or Object.hasOwn when the difference matters:
const partial = { name: "Ana", nickname: undefined };
console.log(partial.nickname, partial.age); // both undefined
console.log("nickname" in partial, "age" in partial);
console.log(Object.hasOwn(partial, "nickname")); // ES2022
console.log(Object.keys(partial));
undefined undefined
true false
true
[ 'name', 'nickname' ]
This matters for updates (does { nickname: undefined } mean "clear the nickname" or "don't change it"?), and it's why APIs often use null explicitly for "clear this field".
Which one should you use?
A practical convention used by many teams:
- Let
undefinedmean "absent", as the language does: unset variables, missing properties, optional parameters. Don't assignundefinedexplicitly; leave the property out or omit the argument. - Use
nullfor "intentionally empty" values that you store or send: a cleared selection, "no manager" in a database record, a JSON field that has been deliberately emptied.nullsurvivesJSON.stringify;undefineddisappears. - Check with
== nullor??so both are handled whichever one arrives.
Some codebases (and the TypeScript compiler team) avoid null almost entirely and use undefined everywhere. That's also fine. Consistency matters more than the choice.
Common questions
Why does typeof null return "object"?
A bug in the first JavaScript engine: values carried a type tag in their low bits, objects used tag 0, and null was the null pointer, whose bits were all zero. A later proposal to fix it was rejected because too much existing code depended on it. null is a primitive.
Is null >= 0 true?
Yes, and null > 0 and null == 0 are both false. Relational operators like >= convert null to the number 0, but == has a special rule that null equals only null and undefined. This inconsistency is one more reason to check for null explicitly before comparing numbers.
What does structuredClone or the spread operator do with undefined properties?
They keep them: { ...{ a: undefined } } still has an a property. Only JSON.stringify drops them, which is why a JSON round trip isn't a faithful copy (article 21).
Should a function return null or undefined when there is no result?
Follow the conventions of the platform you're working with. Built-in lookup methods are split: Array.prototype.find returns undefined, while String.prototype.match and document.querySelector return null. In your own code, choose one per codebase and document it; callers can use ?? or == null either way.
Summary
undefinedis the language's "no value assigned";nullis a programmer's "deliberately empty". Both are falsy and the sole values of their types.typeof nullis"object"(a bug kept for compatibility);nullbecomes 0 in arithmetic,undefinedbecomes NaN.- Default parameters and destructuring defaults apply only to
undefined. - Reading a property of either throws a
TypeError; use?.where absence is expected. - Check both with
x == nullorx ?? fallback; usein/Object.hasOwnto distinguish a missing property from one set toundefined. - Pick one convention: commonly
undefinedfor absent,nullfor intentionally empty.
Practice Questions
What does this code return?
JSON.stringify({ a: undefined, b: null, c: [undefined] })
Answer
'{"b":null,"c":[null]}'. Properties whose value is undefined are omitted, but undefined in an array becomes null so the array keeps its length.
What do f(null), f(undefined) and f() return?
function f(x = 1) {
return x;
}
Answer
null, 1 and 1. Default values apply only when the argument is undefined (or missing).
What is null + undefined?
Answer
NaN. null becomes 0 and undefined becomes NaN, and any arithmetic with NaN gives NaN.
Write a check that is true when value is neither null nor undefined.
Answer
value != null, or the more explicit value !== null && value !== undefined.
For which values of data.user do snippet A and snippet B behave the same?
const user = data.user ?? {};
const user = data.user || {};
Answer
Whenever data.user is an object, null or undefined. They differ only for the other falsy values (0, "", false, NaN, 0n, -0), which || replaces and ?? keeps.
Previous: JavaScript Booleans: true, false, Truthy and Falsy Values
Next: JavaScript Symbols: Unique Keys, the Global Registry and Well-Known Symbols

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.