Friday, October 11, 2013

The seven falsy values in JavaScript

JavaScript is different from other languages regarding the evaluation if a value is true or false.
The easiest way is to remember the 7 values that are evaluated to "false".
Here they are (some of them are obvious, some are a bit surprising):
  • undefined
  • null
  • false
  • +0
  • -0
  • NaN
  • "" (empty string)
Everything else (e.g. objects, arrays, numbers, strings, regular Expressions ...) evaluates to "true".

This behavior can be used in different ways, e.g. shortening the check if a jQuery selector returns elements or not:

if ($('#foo').length > 0) {
    ...
}

can also be checked as follows (because jQuery returns an array of length 0 which is evaluated to "false"):

if ($('#foo').length) {
    ...
}

Note that you can produce subtle bugs if you are not aware of the evaluation rules.
Example:

function printLineItem(article, price) {
    if (article && price) {
        console.log("Article: " + article + "Price: " + price);
    }
}

printLineItem("Amiga 500", 999);
printLineItem("5 bitcoins voucher for next purchase", 0);

Bad luck for the customer, he won't get the voucher :-(