Ever wonder what the difference is between null and undefined in JavaScript? Ever been bitten by not understanding it? I’d like to think we all have, because I definitely have. Luckily, they’re not too tricky.

As always, go check out Mozilla’s docs on this stuff. It’s great and comprehensive and they know better than me.

First thing to remember: undefined does not equal null

Undefined

A variable in JavaScript is undefined when it hasn’t been assigned a value yet.

The MDN web docs say this:

A primitive value automatically assigned to variables that have just been declared or to formal arguments for which there are no actual arguments.

When you create a variable but don’t assign anything to it, JavaScript sticks the undefined in it. undefined is actually a JavaScript global property, and one of JavaScript’s primitive types.

    var x;
    console.log("value of x is " + x);

The above code will output:

    > "value of x is undefined"

Null

A variable in JavaScript is null when it has been intentionally assigned null.

The MDN web docs say this:

The value null represents the intentional absence of any object value. It is one of JavaScript’s primitive values.

The key word here is intentional. null indicates that an absence of object has been intentionally set, whereas with undefined, nothing has ever been assigned to a variable.

    var m = "Hi there."
    console.log(m);
    var m = null;
    console.log(m);

The above code will output:

    > "Hi there."
    > null

Does undefined equal null?

Okay, so that’s kind of a trick question. In JavaScript, you should be asking me: “What do you mean by equal?”

    var m = null;
    var t;
    console.log(t == m);

Will output:

    > true

While

    var m = null;
    var t;
    console.log(t === m);

Will output:

    > false

Why? Well, as you hopefully already know, === and == are very different operators.

== is the abstract equality comparison operator, and will do an implicit type conversion

=== is the strict equality comparison operator will compare values, which is usually what you really want. If you want to type convert before comparing values, it’s best to do that explicity so everyone knows what’s going on (including yourself at a later date when you look at old code, or if a bug pops up).

With undefined == null, it’s a bit different, though. If you look at the ECMA specification is because the spec says to specifically return true:

If x is null and y is undefined, return true.

So, that’s it for today!

Until next time: keep meditating, and keep using that strict equality comparison operator :)