Best Practice: Convert 1 and 0 to true and false in Javascript

1 und 0 zu true und false in Javascript

Today there will be only a very short post. There are certainly many ways to convert 0 and 1 in Javascript to true and false.

The following way to reach the wanted result I’ve seen today. I think it is probably the shortest and most elegant way to go. In addition, it works not only for integer values, but also for the string representations of 0 to 1.

So this is the stuff I like to add to my personal “POP”-collection (pearls of programming)…

0 and 1 to true and false

To convert the integers 0 and 1 to boolean, it is sufficient to use the not-operator twice.

var thisIsFalse = !!0; //false
var thisIsTrue = !!1; //true

Why it works? Here is a short explanation. 1 is a valid value and thus true. When we write !1 now, then we create a false condition because 1 isn’t false. With a second ! (so !!1) we negate the resulting false and get thus true for the 1. For the 0 it looks the other way out. So 0 corresponds to false. Negate it !0 to get a true. Do it twice !!0 to get true.

“0”- and “1”-Strings to true and false

And what if 0 and 1 are represented as strings, for example if you have to handle bad formatted JSON string? Nothing could be easier. Using the + operator you can cast the strings to int. Then use the not-operator as shown above. So the solution for strings looks like this:

var thisIsFalse = !!+"0"; //false
var thisIsTrue = !!+"1"; //true

With three characters from string (with the value “0” or “1”) to Boolean. I think there aren’t much paths to get this effect in a more elegant way. But yes, you live and learn. So do you know a better solution? Then share it with me.

1 Comments

  1. Namasays:

    // just compare with “1”:
    var thisIsFalse = “0” === “1”; //false
    var thisIsTrue = “1” === “1”; //true

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked