Steve Jenson's blog

JavaScript undefined vs. null

JavaScript undefined vs. null

I was reading a modern, popular book on JavaScript last night and was disappointed by the handling of null. The author started out doing a lot of checking like:

if (foo == null) {   alert('foo is not set.'); }

Then told the reader that they could just remove the == null because javascript knows you mean "== null"

What?! This isn't why you don't check for equality with null. It's because foo == null doesn't even remotely do what most people think it does in this context.

It's a commonly held belief that uninitialized properties in JavaScript are set to null as default values. People believe this mostly for 2 reasons: 1) foo == null returns true if foo is undefined and 2) authors don't teach JavaScript properly.

A property, when it has no definition, is undefined. Put that way, it's pretty obvious.

null is an object. It's type is null. undefined is not an object, it's type is undefined. That part is less obvious.

The real trouble is that == does type coercion. === checks for both type and value and is the most intuitive form of equality in JavaScript, in my opinion.

I fired up a Jash console to hopefully clear things up for you.

    >> window.hello
    null
    >> window.hello.something
    window.hello has no properties
    >> window.hello == null
    true
    >> window.hello === null
    false
    >> window.hello === undefined
    true
    >> if (window.hello) { alert('truthy'); } else { alert('falsy'); } // will print falsy.
    null
    >> window.hello == undefined
    true
    >> null == undefined
    true // there's the rub, sir.
    >> null
    null
    >> undefined
    null
    >> typeof null
    object
    >> typeof undefined
    undefined
    

So people write

    if (foo == null) {
       foo = "Joe";
    }
    
When what they really mean is
    if (!foo) {
       foo = "Joe";
    }
    
If you find yourself with a lot of null checks in your JavaScript, set aside some time and watch Douglas Crockford's "The JavaScript Programming Language" talk on Yahoo Video. It's part 1 of a 3-part series of excellent and enlightening talks.

# — 17 February, 2008