Immediately invoked function expression: Difference between revisions

Content deleted Content added
m Wrapped the ellipsis in comments, this allows the code to be copy + paste friendly.
Usage: ES6
Line 3:
 
==Usage==
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><ref>{{cite web|url=http://exploringjs.com/es6/ch_arrow-functions.html#iiaf|title=ExploringJS|author=Axel Rauschmayer}}</ref>
<syntaxhighlight lang="JavaScript">
(function () { /* ... */ })();
(function () { /* ... */ }());
(() => { /* ... */ })(); // With ES6 arrow functions (though parentheses only allowed on outside)
</syntaxhighlight>