AI Hints
Home›JavaScript Tutorial›Comparing Values
JavaScript · Lesson 15 of 138

null and undefined

Nothing, two ways.

⏱ 2 min read▶ Video at 16:42🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Most languages have one way to say nothing here. JavaScript has two. Undefined, and null. They're similar, but they mean slightly different things.

null and undefined
From the video: null and undefined
  • One way to say nothing?
  • JavaScript has two
  • undefined and null

Two empty values

A variable that's created, but never given a value, is undefined. That's JavaScript saying, nothing was put here. Null is a value you set on purpose, to say, this is intentionally empty. Run it. Both are empty, but they're not exactly equal.

app.jsjavascript
let middleName;
console.log("not set:", middleName);

let selectedItem = null;
console.log("cleared:", selectedItem);

console.log(null === undefined);
Output
not set: undefined
cleared: null
false

When you see them

You'll see undefined when you read a property that doesn't exist, or call a function that doesn't return anything. You use null yourself, when you want to clear a value, like no item selected. Checking for them is so common that modern JavaScript has special operators for it, which we'll meet later.

keyvalue
undefinednever set
nullset to empty on purpose
Missing propertyundefined
Clear a valueuse null

Checking for empty values

A common job is checking whether a value is missing. Comparing with null using two equals catches both null and undefined, which is one of the rare good uses of two equals. And the two question marks operator gives a fallback, only for null or undefined. Run it.

app.jsjavascript
let nickname;
let middleName = null;
const age = 0;

console.log(nickname == null, middleName == null, age == null);
console.log(nickname ?? "no nickname");
console.log(age ?? "no age");
Output
true true false
no nickname
0

Summary

Undefined means no value was ever set, and null means empty on purpose. Next, checking a value's type with typeof.

Key takeaways
  • undefined: not set
  • null: empty on purpose
  • null !== undefined
Next up: typeof — what type is it?