Immediately invoked function expression: Difference between revisions

Content deleted Content added
m Douglas Crockford did not invent or coin his own function invocation syntax. That was deliberately designed and defined by the grammar of ES3
Tag: references removed
m Wrapped the ellipsis in comments, this allows the code to be copy + paste friendly.
Line 5:
Immediately-invoked function expressions may be written in a number of different ways.<ref name=Enlighten>{{cite book|last=Lindley|first=Cody|title=JavaScript Enlightenment|year=2013|publisher=O'Reilly|isbn=9781449342883|pages=61}}</ref> A [[Coding conventions|common convention]] is to enclose the function expression (and optionally its invocation operator) with the ''grouping operator'',<ref>{{cite web|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping|title=Grouping operator|publisher=Mozilla Developer Network}}</ref> i.e. in parentheses, to explicitly tell the parser to expect an expression. Otherwise, in most situations, when the parser encounters the <code>function</code> keyword, it treats it as a function declaration (statement), and not as a function expression.<ref>{{cite book|last=Zakas|first=Nicholas|title=Maintainable JavaScript|year=2012|publisher=O'Reilly|isbn=9781449327682|pages=44}}</ref>
<syntaxhighlight lang="JavaScript">
(function () { /* ... */ })();
(function () { /* ... */ }());
</syntaxhighlight>
 
There are other ways to enforce a function expression:
<syntaxhighlight lang="JavaScript">
!function () { /* ... */ }();
~function () { /* ... */ }();
-function () { /* ... */ }();
+function () { /* ... */ }();
void function () { /* ... */ }();
</syntaxhighlight>
 
In contexts where an expression is expected, wrapping in parentheses is not necessary:
<syntaxhighlight lang="JavaScript">
var f = function () { /* ... */ }();
true && function () { /* ... */ }();
0, function () { /* ... */ }();
</syntaxhighlight>
 
Passing variables into the scope is done as follows:
<syntaxhighlight lang="JavaScript">
(function(a, b) { /* ... */ })("hello", "world");
</syntaxhighlight>
 
Line 37:
})();
</syntaxhighlight>
…to avoid being parsed as <code>c()</code>.
 
==Examples==