Immediately Invoked Function Expression
   HOME

TheInfoList



OR:

An immediately invoked function expression (or IIFE, pronounced "iffy", IPA /ˈɪ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. It was popular in
JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
as a method of supporting
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 or "concern" of the d ...
before the introduction of more standardized solutions such as
CommonJS CommonJS is a project to standardize the module ecosystem for JavaScript outside of web browsers (e.g. on web servers or native desktop applications). CommonJS's specification of how modules should work is widely used today for server-side Jav ...
and ES modules. Immediately invoked function expressions can be used to avoid variable hoisting from within blocks, protecting against polluting the global environment and simultaneously allowing public access to methods while retaining privacy for variables defined within the function. In other words, it wraps functions and variables, keeping them out of the global scope and giving them a local scope.


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) 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"); (function(a="hello", b="world") )(); //also works An initial parenthesis is one case where the automatic semicolon insertion (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 (programming languages), 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 s ...
. 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. // Before ES6: Creating a scope using an IIFE var foo = 1; var bar = 2; (function())(); console.log(foo, bar); // 1 4 // Since ES6: Creating a scope using curly brackets in combination with let and const const foo = 1; let bar = 2; console.log(foo, bar); // 1 4


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 (computer science), statement for specifying iteration. Specifically, a for-loop functions by running a section of code repeatedly until a certain condition has been satisfi ...
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 standard for scripting languages, including JavaScript, JScript, and ActionScript. It is best known as a JavaScript standard intended to ensure the interoperability of web pages across different web browsers. It is stan ...
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 nam ...
.


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 ...


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