Reputation: 11257
I have been studying IIFE(Immedately-Invoked Function Expression) and understand the general pattern and how it works:
(function boo(y) {
alert(y);
})(2); // call, not a grouping operator, 2
In this case:
function body(y){
alert(y);
}(2);
The (2) is just a grouping operator,It has nothing to do with invoking the function statement it is the same as:
function body(y) {
alert(y);
}
(2);
I don't understand how these two functions create a Function Expression instead of a function statement:
2, function () {
alert('anonymous function);
}();
// OR
!function () {
alert('Hello World');
}();
How are these two functions acting as expressions? I can see them being anonymous functions, but I don't understand how they are expressions? Why are they being executed instead of throwing some form of a syntax error?
Upvotes: 2
Views: 268
Reputation: 10972
First, none of your examples are called "function statement". That's a Mozilla-only distinction for syntax that looks like a function declaration, but appears in a statement block.
In this case:
function body(y){ alert(y); }(2);The (2) is just a grouping operator,It has nothing to do with invoking the function statement...
Yes, the (2)
would be a grouping operator because the function declaration is hoisted, so the (2)
doesn't really follow it.
...it is the same as:
function body(y) { alert(y); } (2);
Yes, the whitespace is ignored.
I don't understand how these two functions create a Function Expression instead of a function statement:
2, function () { alert('anonymous function); }();// OR
!function () { alert('Hello World'); }();
They're an expression because of the presence of an operators that require expressions for their operand(s). As such, the function becomes the operand, and so is evaluated as the required expression.
So it's merely that when the program is parsed, and encounters for example the !
, it knows that what comes next must be an expression, and so when it evaluates the function () {...
that comes after it, it sees that as a valid expression, and so interprets it as such.
Upvotes: 2