Harry Cresswell

Understanding data types: null vs undefined

These notes are taken from Beginner JavaScript by Wes Bos. Go buy it!

There are two ways to express nothing in JavaScript; null and undefined. But how do they differ?

Understanding undefined #

If we create a variable but don’t set anything to it, the value returned will be undefined.

let dog;
console.log(dog);

undefined is something that has been created, like a variable, but does not yet have a value set to it. In other words, it is not yet defined.

The browser sets this missing value to undefined because no value exists and so there is nothing to return.

If we then give the variable a value:

dog = "snickers";

The browser will return the new value:

dog;
("snickers");

And the value is no longer undefined.

Understanding null #

null is a value of nothing that has to be explicitly set before it can be returned as null.

const somethingNull = null;

In this case the value is null, unlike our example above which is undefined because it literally has no value.

let somethingUndefined;

This example returned undefined as we have yet to give it a value.

A practical example #

We can use the example of a mononymous person (someone known by a single name). In this case we’ll use the singer Cher, who we know only as Cher.

const cher = {
  first: "cher"
};

We don’t know Cher’s last name so .last will return undefined.

cher.last;
undefined;

Now on to our example of null.

The comedian and illusionist Teller, the silent half of the duo Penn & Teller, legally changed his original polynym, Raymond Joseph Teller, to the mononym “Teller” and possesses a United States passport issued in that single name.

In JavaScript we can represent his original name like this:

const teller = {
  first: "Raymond",
  last: "Teller"
};

To represent his legally changed polynym we might update the value of last to null.

teller.first = "Teller";
teller.last = null;

That’s it.

Weekly Newsletter

Braintactics is a weekly roundup of articles, tools and tips for product designers and front-end developers. I send it every Friday morning.