The Truth About False in JavaScript

By March 14, 2014JavaScript

The distinction between true and false is a blurry line in JavaScript. This is why you hear the term “truthy/falsy” in the JavaScript world. As a follow up to Noel’s blog post, I would like to focus only on one side of the coin. It was inspired by a pop quiz from my teammate, Jesse Liberty.

Welcome to the False Side

What does false really mean in JavaScript? To sum it up, zeros and empty:

false == 0 //true
false == '0' //true
false == '' //true
false == [] //true
false == [[]] //true
false == [0] //true
false == 000 //true
false == '000' //true
false == false //true
false == null //false
false == undefined //false

There’s a twist to this though. Although false == ‘0’ and false == ”, ‘0’ does NOT equal ”. Is this a glitch in the matrix or did JavaScript just tell transitive property to go fly a kite??

0 == '' //true
'0' == '' //false

If your head isn’t spinning yet, it works completely different when using these values in an if-statement:

if (0) //false
if ('0') //true
if ('') //false
if ([]) //true
if ([[]]) //true
if ([0]) //true
if (000) //false
if ('000') //true

Moral of the Story

Use three equals unless you’re fully conscious of what you are doing:

false === 0 //false
false === '0' //false
false === '' //false
false === [] //false
false === [[]] //false
false === [0] //false
false === 000 //false
false === '000' //false
false === false //true
false === null //false
false === undefined //false

Bonus

You can isolate this mess into a utility function so you don’t have to deal with it every time. This allows you to define your own rules and stay consistent:

Helpers: {
   
    isNullOrEmpty: function (value) {
        return typeof value === 'undefined' || value === null || value.length === 0;
    },
       
    convertToBoolean: function (value) {
        //VALIDATE INPUT
        if (typeof value === 'boolean') return value;
        if (this.isNullOrEmpty(value)) return false;
 
        //DETERMINE BOOLEAN VALUE FROM STRING
        if (typeof value === 'string') {
            switch (value.toLowerCase()) {
            case 'true':
            case 'yes':
            case '1':
                return true;
            case 'false':
            case 'no':
            case '0':
                return false;
            default:
                return false;
            }
        }
 
        //RETURN DEFAULT HANDLER
        return Boolean(value);
    }
}
 
//HOW TO USE
if (Helpers.convertToBoolean(whateverValue)) {
  //DO YOUR THANG
}

HAPPY CODING!!

References

The following two tabs change content below.