Thursday, September 24, 2009

JavaScript - Anything is a Boolean

There is a JavaScript Trick out there that if discovered, is probably being misunderstood. The trick is to force convert any value into a boolean variable using the double not (!!) operation as follows:
var myBoolean1 = "abc"; //you end up with a String type
var myBoolean2 = !!"abc"; //you end up with a boolean type
However, watch closely as here are the results of each use:
equals(true, !!"some text", "Any non-empty String results in true");
equals(true, !!"False");
equals(true, !!"false");
equals(true, !!"True");
equals(true, !!"true");
equals(true, !!"null");
equals(false, !!"", "JavaScript treats if ('') as false");
equals(false, !!null, "JavaScript treats if (null) as false";
equals(ERROR, !!MyObject, "Throws exception because undefined object";
var MyObject = null;
equals(false, !!MyObject, "JavaScript treats any null object as false";
equals(true, !!window, "JavaScript treats any non-null object as true";
equals(true, !!32, "Any non-zero number results in true");
equals(true, !!1);
equals(false, !!0, "Hopefully as you expected since everything is binary");
equals(false, !!false, "As expected");
equals(true, !!true, "As expected");

No comments:

Post a Comment