Javascript, Booleans, and Implicit/Explicit Casting Performance

Ahh the variant. It provides so much ease in writing code, and yet can cause so many headaches. In Javascript, I learned today what joys and pains of assumption of datatypes through boolean expressions can provide. Take the following simple statement:

var x=true;
var y=false;
if (x || y)
  alert('true');

In this case, x is ORed with y, resulting in an obvious true. But we're assuming boolean values. What happens when one has the possibility of not being boolean?

So the creators of javascript saw in their wisdom to add strong-ish typed declarations. You can declare a boolean explicitly, like so:

var isInAGoodState = new Boolean(true);

So all is happy and we can use good booleans. However, there's also an implicit declaration that's much better in terms of performance:

var isInAGoodState = !!(sourceValue);

Essentially saying not-not-sourceValue, using a double negative, results in a true statement. The amazing thing here is just the scale of the performance gain. From a source example, "Overall, the performance gain for using implicit conversion averaged out to 53% across browsers after 10 tests"

Posted on 10/23/2008 7:16:00 PM by Jason Nadal

Permalink | Comments |

Categories: development | javaScript

Tags: ,

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
blog comments powered by Disqus