Possible Duplicates:
What is the difference between a function expression vs declaration in JavaScript?
Explain JavaScript's encapsulated anonymous function syntax
Why this:
(function () {
//code
}());
and this:
var f = function () {
//code
}();
works, while this:
function () {
//code
}();
does not? It looks exactly the same - anonymous function defined, and immediately called. Can someone make a quotation from the JavaScript/ECMAScript standard which explains that?
UPDATE: Thanks for the answers everyone! So it's about function expression vs. function declaration. See this Stack Overflow answer, ECMAScript standard section 13, and this great article: Named function expressions demystified.
To recap answers:
The first snippet is interpreted as an expression because the grouping operator,
()
, is applied - see ECMAScript standard section 11.1.6.In the second snippet, the function is interpreted as an expression because it's on the right-hand part of assignment operator,
=
.The third snippet doesn't have anything which allows the interpreter to read the function as an expression, so it's considered a declaration, which is invalid without an identifier (Gecko lets it pass however, but it chokes on following
()
grouping operator (as it thinks) applied to nothing).