HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

3) Learn to Crawl Before You Can Run Lesson

Understanding the Difference Between Null and Undefined in JavaScript

4 min to complete · By Ian Currie

In this lesson you will learn about what undefined and null mean, and the difference between these two data types.

While these two data types are very similar, they have some distinct differences that are important to note.

What Is the Difference Between Null and Undefined

Try this out in the console, what do you expect to see?

let empty;
console.log(empty);
Undefined and Null

This image gives you an idea of the difference between 0, null and undefined.

Undefined

First up is the undefined data type. This is the default data that is assigned to a variable when it is initialized.

When you declare a variable with let and do not immediately assign a value to the variable, JavaScript automatically assigns the variable the undefined data type. Or, better said, since it has no data assigned to it, whenever the variable is read, it comes up as undefined. So this data type is essentially the absence of data, meaning the variable exists, but it is as yet empty.

Null

The null data type is when you deliberately want an assignment of an empty value. Unlike undefined, null has to be set by the developer explicitly. null represents an empty value; the variable has a value and that value is null, which signals an intent to communicate that it has "no value". It is something like the concept of zero, although zero is an integer, and therefore it has some meaning. null is more like nothingness! null is often used when a search function returns nothing. It can't find a match, and needs to return 'something', so it returns the value null.

let match = null;
match = findMatch(list);
Illustration of a lighthouse

The code example demonstrates a potential use of null. You initialize a variable with null to denote that it is intentionally empty. After attempting to find a match, if the variable remains null, you know the function didn’t find what it was looking for.

Summary: Javascript Null vs Undefined

  • null and undefined are two distinct data types

Undefined

  • undefined is the default data that is assigned to a variable when it is declared.
  • When you create a variable without a value, Javascript automatically assigns it the value of undefined
  • undefined basically means the absence of data

Null

  • null is a deliberately assigned value that signals an empty value
  • It differs from zero since zero is an integer, and therefore is has some meaning