What parentheses are doing after declaration of a function (last line)?
var a = 0;
function foo(a) {
alert(a);
} (a);
What parentheses are doing after declaration of a function (last line)?
var a = 0;
function foo(a) {
alert(a);
} (a);
That code looks a bit tricky, because it declares a variable, assigns it a value, declares a function (that happens earlier, but it's third in the code), then has an expression that does nothing. Let's break it down:
First, it declares the variable a
and assigns 0
to it:
var a = 0;
Then it declares a function:
function foo(a) {
alert(a);
}
Then it has this expression, which does nothing:
(a);
The key thing here is that the function declaration is a declaration, not an expression, and so the (a)
that follows it does not apply to it. JavaScript has function declarations, and function expressions. Function declarations always have a function name; function expressions can be named or anonymous.
If we change the code slightly, we can make that a function expression, which means the (a)
would call the function:
var a = 0;
(function foo(a) {
alert(a);
})(a);
The opening (
puts the parser in a mode where it expects an expression, which changes function declaration into a function expression (specifically, a named one). Which means we can immediately call the function by putting (a)
after it.
There are lots of ways to put the parser into the mode where it expects an expression, parens is just one way. You could also use any unary operator:
var a = 0;
(function foo(a) {
alert(a);
})(a);
You can tell whether something is a function declaration or a function expression by whether it's being used as what's called a right-hand value; that is, is it being assigned to something, passed into a function, having an operator applied to it (at the beginning), etc.
Here's a function declaration:
function foo() {
}
and here's a named function expression (which it's best to avoid on IE8 and earlier)
var f = function foo() {
};
(note how we're using the value immediately, assigning the function to f
)
...and here's an anonymous function expression:
var f = function() {
};