Quick Tip: Truthy/Falsy to True/False

, ,

You may already know about truthy/falsy, but this is basically the concept that certain things in javascript equate to either true or false. E.g. an empty string equates to false. However, sometimes truthy/falsy isn’t enough, and we actually need the Boolean value.

A simple quick tip to convert a truthy/falsy value to its Boolean counterpart is this:

var falsyString = "";
var realFalse = !!falsyString;
// falsyString equates to false, realFalse is the actual Boolean value false

All this does is double-negate the falsy value of falsyString using the logical NOT operator (!). The first negation turns falsyString into the Boolean value true, then we negate it again to return it to its original state but now as the Boolean value false.

Obviously this works for truthy as well as falsy… Go forth and seek the true truth!