22. Null and Undefined

In This Chapter

  • Learn about when values don’t exist

  • Understand what to do with null and undefined

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 particularly bizarre. It is just dreadfully boring...like the most boring (yet important) thing about JavaScript you’ll ever have to learn.

Onward!

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:

let name = null;

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

The null primitive isn’t a naturally occurring resource. It is 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 existence 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;
console.log(myVariable); // undefined

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

let weekendPlans = doNothing();
console.log(weekendPlans); // undefined

let person = {
  firstName: "Isaac",
  lastName: "Newton"
}
console.log(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 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:

let myVariable;

if (typeof myVariable === "undefined") {                        
    console.log("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 === weirdness, 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!

The Absolute Minimum

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 are very important skills to get right. Not getting them right will lead to very subtle errors that are going to be hard to pinpoint.

If you have any questions about null and undefined or just want to talk to some of the friendliest developers on the planet to get unblocked, post on https://forum.kirupa.com.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.120.204