In JavaScript, you often see code like this:
// 1
(function() {
a bunch of code;
})();
The code in the function runs immediately and allows you to avoid namespace collisions with other code. If the code includes (inner) functions, those functions are essentially private. In fact, they will go away if there are no references to them when the code completes.
People seem to prefer the above syntax, though the code is equivalent to:
// 2
(function () {
a bunch of code;
}());
When I first felt the need to do this sort of thing, I tried the more intuitive syntax:
// 3
function () {
a bunch of code;
}();
That is what one would expect to work. It makes intuitive and syntactic sense. It clearly creates an anonymous function and then invokes it. However, it causes a syntax error because, according to here, a statement that begins with the function
token must be a function declaration (as opposed to an invokable function expression).
Noting first that the following works without complaint:
// 4
var discard = function () {
a bunch of code;
}();
I then arrived at this:
// 5
void function () {
a bunch of code;
}();
Note that void
is a unary operator in JavaScript that discards its operand and evaluates to undefined
. It is neither a function, as has been misreported, nor a data type, nor the absence of a data type, as it is in Java.
To me, #5 is more readable than #1 and #2. What I don’t like about #5 is that it’s still a bit cryptic. It may be cryptic, but I think it’s less syntactically disconcerting than #1 and #2, where I really don’t like the mysterious outer parentheses.
In case you missed it
Cases #1, #2, and #5 are equivalent. To me, #5 looks the simplest and the least prone to errors. I do wonder if there any insidious differences deep under the hood of any browsers.
Encapsulation? Or clean air?
This is a technique in JavaScript commonly used to avoid namespace pollution, and it’s often referred to as encapsulation, even though it’s really not. Booch defines encapsulation as “serving to separate the contractual interface of an abstraction and its implementation.” To this end, in Java and ActionScript, we have the interface. In JavaScript, we don’t.
Notes
- 2012-11-20. Douglas Crockford refers to case #1 as “dog balls” here and prefers case #2.
Leave a Reply