Monday, March 30, 2009

Javascript : Anything can convert to Boolean!

Most powerful languages are very simple to program and very complex to master. and no doubt Javascript is one among them!

As Javascript as minimal data types, and in times anything can be potentially converted to boolean value, and the reason is few values [0, false, '',undefined, null] are equate themselves to boolean FALSE.

So, here is an example to convert any data type to equate to a boolean value.

var val=5;
val=!!val;
alert('Numeric Value:'+val); //true

val=0;
val=!!val;
alert('Zero Numeric Value:'+val); //false

val = '';
val =!!val;
alert('Empty space value:'+val); //false

val = undefined;
val = !!val;
alert('undefined value:'+val); //false

val = new Array();
val=!!val;
alert('Array Object value:'+val); //true

val= {};
val=!!val;
alert('Empty Object value:'+val); //true

val=false;
val=!!val;
alert('Boolean value:'+val);  //false

val= null;
val=!!val;
alert('Null value:'+val); //false




Albeit this power can mislead to type safety, it certainly adds great value when used wisely.

Hope you do so :-)

No comments: