Monday, December 13, 2010

Coerced.

The !! "operator" in JavaScript can be superficially useful to force type coercion and cast to bool.

It's generally a neat trick.  Since null == false, then !!null === false; !!0 === false; !!'cat' === true; etc.  

So, if s is one of {null, '', '0', '1'}, will !!s === true only when s === '1'?

While it's true that '0' == 0 and '0' == false, !'0' is also == false.  That is to say... '0' == !'0', and thus !!'0' === true.   The type coercing effects of "!" are different from the type coercing effects of "== false". 

So.. No.

Workaround?  Well, !!Number(s) will work as !! was meant to, as will !('0' == false).   Better workaround?  Don't think you can master type coercion, no matter how much you think you know javascript, Jude, because you are wrong.

0 comments: