Ajax Bestiary: A Javascript Field Guide
 
Ajax Bestiary: A Javascript Field Guide
 
 

!! You’re True (or False)

Posted by Don Albrecht

Ok, so you probably know that Javascript like most other programming languages treats “0″ as false and any other numerical value as true in logic statements. Usually, this is sufficient, unfortunately, sometimes, you need a bit more consistent behavior. For example, ( 2 && 3 && true ) = 2.

Luckily there is a simple fix. Since, ! only operates on boolean data. !(0) is true and !( any other non-null value is false). Therefore, !! returns the boolean value of the original expression.

Another way of coding it, would be “Boolean ( expression );” and directly casting the expression to a Boolean. All things being equal, this would honestly be my preferred way of doing it. After all, legibility in code is one of the utmost considerations for most development, but since bandwidth is also a major consideration in javascript and !! is reasonably intuitive, I personally use it wherever necessary.

Related Posts


Leave a Reply