(function(a, b) {
var x;
})
returns an anonymous function. For technical/historical reasons, anonymous functions must be wrapped in parentheses.
Notably, the names a
,b
and x
are not visible to outside code. In contrast, just writing var x;
would make x
accessible and thereby pollute the global namespace. This is the equivalent of private variables in classical object-orientated languages.
We could also write:
var func = function(a, b) {var x;};
// or equivalently:
function foo(a, b) {var x;};
func('arg1', 2);
but that would again pollute the global namespace by making a function func
visible for everyone else. Since we don't want to call func
more than once anyway,
(function(a, b) {var x;}) ('arg1', 2);
is the perfect way to execute code with variables without making these variables(or any variable names) visible to the rest of the world.