The KIRUPA orange logo! A stylized orange made to look like a glass of orange juice! Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Table of Contents

null and undefined

by kirupa   |   filed under JavaScript 101

One of the great mysteries of the world revolves around making sense of null and undefined. Most code you see is littered with them, and you've probably run into them yourself a few times. As mysteries go, making sense of null and undefined isn't particulary bizarre. It is just dreadfully boring...like the most boring (yet important) thing about JavaScript you'll ever have to learn.

Onwards!

Null

Let's start with null. The null keyword is a primitive that fills a special role in the world of JavaScript. It is an explicit definition that stands for no value. If you've ever browsed through code others have written, you'll probably see null appear quite a number of times. It is quite popular, for the advantage of null lies in its definitiveness. Instead of having variables contain stale values or mystery undefined values, setting it to null is a clear indication that you want the value to not exist.

This advantage is important when you are writing code and want to initialize or clear a variable to something that represents nothing.

Here is an example:

var name = null;

if (name === null) {
	name = "Peter Griffin";
} else {
	name = "No name";
}

The null primitive isn't a naturally occuring resource. It is something something you consciously assign, so you will often see it used as part of variable declarations or passed in as arguments to function calls. Using null is easy. Checking for its existience is pretty easy as well:

if (name === null) {
	// do something interesting...or not
}

The only thing to note is that you should use the === operator instead of the lowly == one. While the world won't end if you use ==, it's good practice to check for both type and value when working with null.

Undefined

Here is where things get a little interesting. To represent something that isn't defined, you have the undefined primitive. You see undefined in a few cases. The most common ones are when you try to access a variable that hasn't been initialized or when accessing the value of a function that doesn't actually return anything.

Here is a code snippet that points out undefined in a few of its natural habitats:

let myVariable;
alert(myVariable); // undefined

function doNothing() {
   // watch paint dry
   return;
}

let weekendPlans = doNothing();
alert(weekendPlans); // undefined

let person = {
  firstName: "Isaac",
  lastName: "Newton"
}
alert(person.title); // undefined

In your code, you probably won't be assigning undefined to anything. Instead, you will spend time checking to see if the value of something is undefined. You have several ways to perform this check. The first is a naive way that usually almost always works:

if (myVariable === undefined) {
	// do something
}

The downside of this approach has to do with what undefined actually is. Brace yourself - undefined is a global variable that happens to be automatically defined for us, and this means we can potentially overwrite it to something like true or whatever else we want to set it to. If undefined ever gets overwritten, it would would break our code if we just check with a === or == even. To avoid any shenanigans around this, the safest way to perform a check for undefined involves typeof and the === operator:

var myVariable;

if (typeof myVariable === "undefined") {
    alert("Define me!!!");
}

This ensures that you will perform a check for undefined and always return the correct answer.

null == undefined, but null !== undefined

Continuing the == and === weirdnesses, if you ever check for null == undefined, the answer will be a true. If you use === and have null === undefined, the answer in this case will be false.

The reason is that == does type coercion where it arm twists types to conform to what JavaScript thinks the value should be. Using ===, you check for both type and value. This is a more comprehensive check that detects that undefined and null are indeed two different things.

A hat tip to senocular (aka Trevor McCauley) for pointing this out!

Conclusion

There is a reason why I saved these built-in types for last. Null and undefined are the least exciting of the bunch, but they are also often the ones that are the most misunderstood. Knowing how to use null and detecting for it and undefined is a very important skill to get right. Not getting it right will lead to very subtle errors that are going to be hard to pinpoint.

Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends