HOME

TheInfoList



OR:

An immediately invoked function expression (or IIFE, pronounced "iffy",
IPA IPA commonly refers to: * India pale ale, a style of beer * International Phonetic Alphabet, a system of phonetic notation * Isopropyl alcohol, a chemical compound IPA may also refer to: Organizations International * Insolvency Practitioners ...
/ˈɪf.i/) is a programming language idiom which produces a
lexical scope In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
using
function scoping In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
. It was popular in
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
as a method to support
modular programming Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired function ...
before the introduction of more standardized solutions such as
CommonJS CommonJS is a project with the goal to establish conventions on the module ecosystem for JavaScript outside of the web browser. The primary reason for its creation was a major lack of commonly accepted forms of JavaScript module units which could ...
and ES modules. Immediately invoked function expressions can be used to avoid
variable hoisting The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program. The examples below make use of the log function of the console object present in most browsers for standard text output. The JavaScript stand ...
from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.


Usage

Immediately invoked function expressions may be written in a number of different ways. A common convention is to enclose the function expressionand optionally its invocation operatorwith the grouping operator, in parentheses, to tell the parser explicitly to expect an expression. Otherwise, in most situations, when the parser encounters the function keyword, it treats it as a function declaration (statement), and not as a function expression. (function () )(); (function () ()); (() => )(); // With ES6 arrow functions (though parentheses only allowed on outside) There are other ways to enforce a function expression: !function () (); ~function () (); -function () (); +function () (); void function () (); delete function () (); typeof function () (); await function () (); In contexts where an expression is expected, wrapping in parentheses is not necessary: let f = function () (); true && function () (); 0, function () (); Passing variables into the scope is done as follows: (function(a, b) )("hello", "world"); An initial parenthesis is one case where the
automatic semicolon insertion In computer science, lexical analysis, lexing or tokenization is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of ''lexical tokens'' ( strings with an assigned and thus identified ...
(ASI) in JavaScript can cause problems; the expression is instead interpreted as a call to the last term on the preceding line. In some styles that omit optional semicolons, the semicolon is placed ''in front'' of the parenthesis, and is known as a
defensive semicolon The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program. The examples below make use of the log function of the console object present in most browsers for standard text output. The JavaScript stan ...
. For example: a = b + c ;(function () )(); ...to avoid being parsed as c().


Examples

The key to understanding design patterns such as IIFE is to realize that prior to ES6, JavaScript only featured
function scope In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
(thus lacking
block scope In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
), passing values by reference inside closures. This is no longer the case, as the ES6 version of JavaScript implements block scoping using the new let and const keywords.


Evaluation context

A lack of block scope means that variables defined inside (for example) a
for loop In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied. For-loops have two part ...
will have their definition "hoisted" to the top of the enclosing function. Evaluating a function that depends on variables modified by the outer function (including by iteration) can be difficult. We can see this without a loop if we update a value between defining and invoking the function. let v, getValue; v = 1; getValue = function () ; v = 2; getValue(); // 2 While the result may seem obvious when updating v manually, it can produce unintended results when getValue() is defined inside a loop. Hereafter the function passes v as an argument and is invoked immediately, preserving the inner function's execution context. let v, getValue; v = 1; getValue = (function (x) )(v); v = 2; getValue; // 1 This is equivalent to the following code: let v, getValue; v = 1; function f(x) ; getValue = f(v); v = 2; getValue; // 1


Establishing private variables and accessors

IIFEs are also useful for establishing private methods for accessible functions while still exposing some properties for later use. The following example comes from Alman's post on IIFEs. // "counter" is a function that returns an object with properties, which in this case are functions. let counter = (function () )(); // These calls access the function properties returned by "counter". counter.get(); // 0 counter.set(3); counter.increment(); // 4 counter.increment(); // 5 If we attempt to access counter.i from the global environment, it will be undefined, as it is enclosed within the invoked function and is not a property of counter. Likewise, if we attempt to access i, it will result in an error, as we have not declared i in the global environment.


Terminology

Originally known as a "self-executing anonymous function", Ben Alman later introduced the current term IIFE as a more semantically accurate name for the idiom, shortly after its discussion arose on comp.lang.javascript. Notably, immediately invoked functions need not be anonymous inherently, and
ECMAScript ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262 ECMAScript is commonly used for client-side scripting o ...
5's strict mode forbids arguments.callee, rendering the original term a
misnomer A misnomer is a name that is incorrectly or unsuitably applied. Misnomers often arise because something was named long before its correct nature was known, or because an earlier form of something has been replaced by a later form to which the name ...
.


See also

*
Evaluation strategy In a programming language, an evaluation strategy is a set of rules for evaluating expressions. The term is often used to refer to the more specific notion of a ''parameter-passing strategy'' that defines the kind of value that is passed to the f ...


References


External links

* {{cite web , title=Functions and function scope , url=https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope , work=Mozilla JavaScript Reference , publisher=Mozilla Developer Network , accessdate=4 February 2013 JavaScript Programming language concepts