Saturday, January 17, 2009

Javascript fun

Unlike most Googlers, I have very little experience with JavaScript. I've only recently started dabbling and it's quite an experience. Many, many articles have been written on all the cool/bizarre quirks of the language, so I won't repeat them here. Instead, I'll point out a couple of tiny things that I ran into recently that are kind of cool/bizarre.

!!boolean_var - This is really just syntactic sugar, but it is pretty nice. If you want boolean_var to be treated as a boolean, this will nicely cast it from any value (including undefined) to its boolean negation and back, so you're guaranteed that boolean_var is a boolean.

arguments fun - The javascript "arguments" object is quite handy, but it can be pretty tricky. Consider these two definitions of a simple function to add 2 or more values:

>>> addAll = function(x, y) { 
      if (x != null && y != null) { 
        for (b = 1; b <>
          x += arguments[b]; 
        } 
      } 
      return x; 
    }; 

>>> addAll2 = function(x, y) { 
      if (x != null && y != null) { 
        for (y = 1; y <>
          x += arguments[y]; 
        } 
      } 
      return x; 
    }; 

>>> addAll(10, 2, 4, 6);
22
>>> addAll2(10, 2, 4, 6);
21


The first method works nicely but the second one fails. At first glance, it might appear the second method should work fine since "y" is not accessed after the null check, but notice that "y" and "arguments[1]" are aliased to the same variable, so using "y" as the loop iterator will mess things up. This is not a very common case, but if you're trying to optimize the javascript by avoiding unnecessary variable declarations, these details become quite important.  Be careful out there!