Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 156 ยท Data Types

null and undefined

Understand the difference between null and undefined in JavaScript, where each one appears, and the safest ways to check for missing values.

Most languages have one value that means "nothing here". JavaScript has two: undefined and null. They behave almost the same in conditions, they print differently, and they come from different places โ€” which leads to plenty of confusion and many "cannot read properties of undefined" errors.

The good news is that the difference is simple once you see it. undefined is what JavaScript itself gives you when something has no value yet. null is what programmers use to say "intentionally empty". This lesson shows where each one comes from, how they compare, and how to check for them safely.

undefined: "no value was given"

undefined is the default. JavaScript produces it automatically in several situations:

JS Where undefined comes from

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In every case nobody said what the value should be, so JavaScript filled in undefined. Notice that reading a missing property does not throw an error โ€” it quietly returns undefined. The error only comes when you go one step further and read a property of that undefined:

JavaScript
user.email;          // undefined โ€” fine
user.email.length;   // TypeError: Cannot read properties of undefined (reading 'length')

This is one of the most common error messages in JavaScript. When you see it, look at the expression just before the property named in the message โ€” that's the part that was undefined.

null: "deliberately empty"

JavaScript almost never creates null on its own. It appears when someone chooses to put it there โ€” you, or the author of an API you call. It means "there is intentionally no value":

JS Where null comes from

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the browser you'll meet null often: document.querySelector() returns null when no element matches, and localStorage.getItem() returns null for a missing key. JSON has null too, while it has no undefined at all โ€” another reason APIs prefer null for "empty".

A common convention, and a good one to follow:

  • Let undefined mean "not set yet / doesn't exist" โ€” leave it to the language.
  • Use null when you want to explicitly store "no value", such as clearing a selection.

The typeof null bug

typeof gives a surprising answer for null:

JS typeof null and undefined

Press Run (or Ctrl + Enter) to see the console output here.

No output.

typeof null returning "object" is a bug from the very first version of JavaScript. Fixing it would break existing websites, so it stays forever. null is a primitive, not an object. The practical lesson: don't use typeof to check for null โ€” compare with === null instead. (You saw the other quirks of typeof in Data Types.)

The last line shows something useful: typeof is the one operation that works on a variable that was never declared. Reading such a variable normally throws a ReferenceError, but typeof returns "undefined". You'll rarely need this in modern code, but you'll see it in older scripts that check whether a library is loaded.

Comparing null and undefined

With strict equality (===), null and undefined are different values. With loose equality (==), they are equal to each other โ€” and to nothing else:

JavaScript
null === undefined;  // false
null == undefined;   // true

null == 0;           // false
undefined == false;  // false
null == "";          // false

This special rule makes value == null a compact way to ask "is this null or undefined?" โ€” the one place where many style guides allow ==. You'll learn the rest of the equality rules in Comparison and Equality.

Notice that null == 0 is false, even though null turns into 0 in arithmetic. Loose equality has a special rule for null and undefined instead of converting them to numbers. That inconsistency is one more reason to prefer === everywhere else.

They also behave differently in arithmetic, which can hide bugs:

JavaScript
null + 1;        // 1   (null becomes 0)
undefined + 1;   // NaN (undefined becomes NaN)

Checking for missing values

Which check you write depends on what you want to catch:

You want to knowโ€ฆ Write
Is it exactly undefined? value === undefined
Is it exactly null? value === null
Is it null or undefined? value == null or value === null || value === undefined
Is it any falsy value? !value
JS Choosing the right check

Press Run (or Ctrl + Enter) to see the console output here.

No output.

(String(value) is used for the label because padEnd() is a string method, and null and undefined have no methods of their own.)

The == null column is true exactly for null and undefined, while !value also catches 0 and "". When 0 or an empty string are valid data, the truthiness check from Booleans and Truthiness is too broad.

Missing property or property set to undefined?

An object can have a property whose value is undefined, which looks the same as a property that doesn't exist. When the difference matters, ask about the key, not the value:

JavaScript
const settings = { theme: undefined };

settings.theme === undefined;       // true
settings.font === undefined;        // true โ€” can't tell them apart

"theme" in settings;                // true
Object.hasOwn(settings, "font");    // false

The in operator and Object.hasOwn() are covered in Working with Objects.

Default values for missing data

A frequent job is replacing a missing value with a default. Default parameters do that for undefined arguments:

JavaScript
function greet(name = "friend") {
  return `Hello, ${name}!`;
}

greet();           // "Hello, friend!"
greet(undefined);  // "Hello, friend!"
greet(null);       // "Hello, null!" โ€” null is a deliberate value

Notice that null doesn't trigger the default: passing null counts as passing a value. For a default that covers both null and undefined, JavaScript has the ?? operator, and for safely reading through possibly missing objects it has ?.. Both are covered in Nullish Coalescing and Optional Chaining.

Avoid assigning undefined yourself. If you want to say "empty", use null. That way, when you see undefined while debugging, you know the language produced it โ€” something was never set โ€” rather than having to wonder whether your own code put it there.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a function return if it has no return statement?

    Without return, every function call produces undefined.
  2. 2. What does typeof null return?

    It returns "object", a bug kept for compatibility. Use value === null to check for null.
  3. 3. Which expression is true for both null and undefined, but false for 0 and ""?

    Loose equality treats null and undefined as equal to each other and to nothing else.
  4. 4. Given const user = {}, what does user.address.city do?

    user.address is undefined, and reading .city from undefined throws "Cannot read properties of undefined".

Summary

  • undefined is JavaScript's automatic "no value": unset variables, missing properties and parameters, functions without return.
  • null is an intentional "empty" that you (or an API) assign on purpose.
  • typeof null is "object" โ€” a historical bug. Check with === null.
  • null == undefined is true, so value == null catches both; === keeps them apart.
  • Default parameters replace only undefined; use ?? (covered later) to replace both.

Next: Type Conversion and Coercion โ€” how JavaScript turns values from one type into another, on purpose and by surprise.