Best Practice: Convert 1 and 0 to true and 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 […]