Immediately invoked function expression: Difference between revisions

Content deleted Content added
Evaluation context: also fix earlier code
Citation bot (talk | contribs)
Add: date, authors 1-1. Removed parameters. Some additions/deletions were parameter name changes. | Use this bot. Report bugs. | Suggested by Superegz | Category:Programming language concepts‎ | #UCB_Category 12/23
Line 6:
 
== 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=978-1-4493-4288-3 |page=61}}</ref> A [[Coding conventions|common convention]] is to enclose the function expression{{spnd}}and optionally its invocation operator{{spnd}}with the grouping operator,<ref>{{cite web |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping |title=Grouping operator |date=2 October 2023 |publisher=Mozilla Developer Network}}</ref> in parentheses, to tell the parser explicitly 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=978-1-4493-2768-2 |page=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 () { /* ... */ })();
Line 62:
While the result may seem obvious when updating <code>v</code> manually, it can produce unintended results when <code>getValue()</code> is defined inside a loop.
 
Hereafter the function passes <code>v</code> as an argument and is invoked immediately, preserving the inner function's execution context.<ref name=JQ>{{cite book |lastlast1=Otero |firstfirst1=Cesar |last2=Larsen |first2=Rob |title=Professional jQuery |year=2012 |publisher=John Wiley & Sons |isbn=978-1-118-22211-9 |page=31}}</ref>
 
<syntaxhighlight lang="javascript">