Can you explain the reasoning behind the syntax for encapsulated anonymous functions in JavaScript? Why does this work: (function(){})();
but
Great answers have already being posted. But I want to note that function declarations return an empty completion record:
14.1.20 - Runtime Semantics: Evaluation
FunctionDeclaration :
function
BindingIdentifier(
FormalParameters)
{
FunctionBody}
- Return NormalCompletion(empty).
This fact is not easy to observe, because most ways of attempting to get the returned value will convert the function declaration to a function expression. However, eval
shows it:
var r = eval("function f(){}");
console.log(r); // undefined
Calling an empty completion record makes no sense. That's why function f(){}()
can't work. In fact the JS engine does not even attempt to call it, the parentheses are considered part of another statement.
But if you wrap the function in parentheses, it becomes a function expression:
var r = eval("(function f(){})");
console.log(r); // function f(){}
Function expressions return a function object. And therefore you can call it: (function f(){})()
.