Sunday, September 23, 2012

Immediately-invoking functions with an exclamation point in JavaScript

Recently I had to make use of Twitter buttons and I noticed something particularly interesting in their bootstrap code:
!function(d,s,id){var ... }(document,"script","twitter-wjs");

What's interesting to note here is this incantation:
!function () {

}();

Notice how this looks awfully familiar to how one would normally express an immediately-invoked function:
(function () {

}());

In fact, they are fundamentally doing the same thing, yet the former is a byte shorter.


Note that this technique can be accomplished with the other unary operators as well:
-function(){}();
~function(){}();
+function(){}();

What's happening here is that the unary operators are turning a function declaration [function () {}] to a function expression [!function () {}], which can then be immediately-invoked.

One limitation to using this method is that you can't get back the output of the function, unless you are expecting a truthy/falsy value.

This is because the return value is coerced to a boolean when using the exclamation point and negated (since the function invocation has higher precedence, which is why this technique works), and you can't undo that boolean coercion operation on complex types, strings and numbers.

You can however undo the negation operation if you are expecting a truthy/falsy value by simply double negating the output: var truthy = !!function () { return 1; }();