Patently falsey

  • false
  • 0 (zero)
  • "" (empty string)
  • null
  • undefined
  • NaN

In JavaScript, what do all of the above values have in common? If you guessed "they are all falsey", you are correct, and you have won yourself a copy of The Hole in the Zero, by M. K. Joseph.

However, it is those last three that I would like to spend some time with now. What do null, undefined and NaN have in common? Well, other than evaluating as false, not a whole lot. They are all unique values (eh, zip it, undefined) and have their own unique qualities.

"Wait," you're saying, "null is like, there's nothing there, right?" Wrong. "Well," you say, "what about undefined? That means there's nothing there. I mean, undefined, like it hasn't been defined." Warmer!

Do this:

> typeof null
< "object"
> typeof undefined
< "undefined"
> typeof NaN
< "number"

"So null is an object? But isn't it an empty object?" Wrong again, as you'll see below, empty objects actually evaluate as truthy. So there's something very special about this null object, but more on that later.

"What about undefined? It is of type undefined?" Bull's eye. undefined is actually a very special "placeholder" for any variable that has been declared, but has not been assigned a value. It represents "no value". It is also the default return value of any function or method. It is one of JavaScript's primitive types. However, unlike many primitives, it is not a reserved word. In some cases, you can actually assign a value to the variable name undefined.

Finally, what about NaN? "Oh, that's not a number." True, it represents that concept. If, for example, you try to call parseInt() on an object or an empty array, your result will be NaN.

But, literally any value, when compared for equality with NaN, will evaluate false. Even NaN, when compared with itself, will evaluate false. This is a quality unique to NaN. So how do you check if something really has the value NaN? Compare it to itself. If the result of this comparison is false, you've got yourself a NaN.

"But what about that null object?" Well, actually the fact that it is even of type object is considered to be a bug in ECMAScript. (Nobody's perfect, right?). "But what is the point? I mean don't we already have undefined for when no value has been assigned?" In a way, yes. But one thing that is different is that null actually represents the value null. This is a subtle, but important difference, from undefined, which represents no value.

That's right, a variable or property assigned the value of null has an actual value. For this reason, APIs often return a value of null for an object that can, but does not, have keys or values, nor does it have the value of an empty object.

As a matter of fact, an empty object evaluates as truthy, as do all other values, including "0" (note the quotes), "false" (again note the quotes), empty functions, and empty arrays.

And as far as further truth on truthiness, I'll leave that to Steven Colbert.