Questions tagged [iife]

In Javascript, an IIFE stands for an Immediately-Invoked Function Expression: a function expression that gets invoked immediately after it is defined, such as (function(){ /* code */ })();

IIFE stands for Immediately-Invoked Function Expression. It is used mainly to describe the pattern in JavaScript where a function expression is executed immediately after it is defined. IIFEs usually have the following syntax in JavaScript:

(function() { /* code */ })();

But there are several other valid ways to form an IIFE mentioned in this answer, such as

(function() { /* code */ }());
new function(){ /* code */ }();

The term IIFE was first proposed by Ben Alman in this article, in which he suggests the pronunciation "iffy". He proposed this term as an alternative to what he calls the "popular but misleading term self-executing anonymous function".

The most common notations used today are (function(){}());, with the invoking parentheses inside the grouping (), and (function(){})();, with the invoking parentheses outside of the group.

Apart from there being a minor semantic difference between the two (the first evaluates to (returnvalue of IIFE), whereas the second evaluates to (defined function)<=(call)) they are both equally valid, though the renowned JavaScript expert Douglas Crockford considers the second notation as being "wrong" and "illogical":

When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.

From Code Conventions for the JavaScript programming Language.

The term IIFE was rapidly adopted by the community after it was first coined at the end of 2010. Simply because it's the most accurate description of the pattern itself:

  • II (Immediately-Invoked): The function is defined, and invoked in one go. That's pretty clear
  • F (Function) It's a function...
  • E (expression): Not just any old function: it's an expression rather than a statement. This is crucial.

The difference between a function definition and a function expression is where the function is defined (sticking to JavaScript for examples).

// Any old function:
function f(arg)
{
    return arg;
}

This function definition will be hoisted to the top of its scope, and be made accessible all over that scope:

console.log(f(123));
function f(n)
{
    return (typeof n);
}

will neatly log number, even though the function seems to be called prior to it being defined.

By turning the function into an expression, the definition cannot be hoisted:

console.log(typeof f);
var f = function()
{
    return 'something';
};
console.log(typeof f);

In this example, the only thing that will be hoisted is the declaration of the variable f. The function definition itself is an expression, in the shape of the right hand operand of an assignment. Assignments are never hoisted, so the code will log undefined, and then function.

To turn this Function Expression into an IIFE, we have to do two things: Make sure the function definition is an expression, rather than a statement. As explained above, this is achieved by wrapping the function in the grouping () operator, or adding a logical- or bitwise operator to the statement, the void prefix or the new keyword.

Notes:

Using the void prefix effectively suppresses the return value of the IIFE, and always returns undefined:

var foo = void function()
{
    console.log('called');
    return 'returnVal';
};
console.log(foo);

Logs called, and then the value of foo -> undefined.

Using the new keyword will affect the call-context (this reference) of the IIFE_: The IIFE will behave as a constructor, returning a new object:

new function()
{
    return this.constructor;
};

will return a reference to the function that was just called.

Specific use cases:

  • IFFE's are often used when passing a function as an argument to another function (most notably to solve the infamous loop problem)
  • Custom constructors often are wrapped in an IIFE, to allow for pseudo (private-) static properties. Variables declared in the IIFE's scope stay in memory for as long as the return value of that IIFE is referenced somewhere. This return value can be an object, with a function that in turn references variables from the IIFE's scope. Here's an example.
  • In some browsers, older versions of Internet Explorer in particular, attaching event handlers directly to DOM references caused memory leaks, owing to Internet Explorer managing the memory for the DOM and its JScript engine separately. The only way around this is to attach listeners in an IIFE. When the script terminates, the GC (Garbage Collector) can flag & swipe the entire IIFE's scope and, with it, all DOM references and event handlers are deallocated.
  • Certain patterns, like the module pattern, requires an IIFE. In this function, the module is built up, and eventually exposed (by assigning a global variable) or returned.
  • Sometimes, the entire script is wrapped in an IIFE, to avoid global variables. This is, however, considered a quick-'n-dirty fix.
588 questions
885
votes
3 answers

JavaScript plus sign in front of function expression

I’ve been looking for information about immediately invoked functions, and somewhere I stumbled on this notation: +function(){console.log("Something.")}() Can someone explain to me what the + sign in front of the function means/does?
jOpacic
  • 9,083
  • 11
  • 31
  • 57
854
votes
29 answers

What is the (function() { } )() construct in JavaScript?

I used to know what this meant, but I'm struggling now... Is this basically saying document.onload? (function () { })();
Exitos
  • 26,972
  • 35
  • 118
  • 168
615
votes
8 answers

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I have been reading a lot of Javascript lately and I have been noticing that the whole file is wrapped like the following in the .js files to be imported. (function() { ... code ... })(); What is the reason for doing this rather than a…
Andrew Kou
  • 6,775
  • 4
  • 19
  • 15
465
votes
19 answers

What is the purpose of a self executing function in javascript?

In javascript, when would you want to use this: (function(){ //Bunch of code... })(); over this: //Bunch of code...
Ej.
  • 4,930
  • 3
  • 16
  • 15
383
votes
19 answers

Why do you need to invoke an anonymous function on the same line?

I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...: // Create a new anonymous function, to use as a wrapper (function(){ // The variable that…
palig
  • 7,381
  • 6
  • 22
  • 18
128
votes
4 answers

Advanced JavaScript: Why is this function wrapped in parentheses?

Possible Duplicate: What is the (function() { } )() construct in JavaScript? I came across this bit of JavaScript code, but I have no idea what to make out of it. Why do I get "1" when I run this code? What is this strange little appendix of (1)…
nerdess
  • 8,263
  • 10
  • 34
  • 45
112
votes
3 answers

Immediate function invocation syntax

There is a JSLint option, one of The Good Parts in fact, that "[requires] parens around immediate invocations," meaning that the construction (function () { // ... })(); would instead need to be written as (function () { // ... }()); My…
Bobby Eickhoff
  • 2,375
  • 2
  • 20
  • 20
107
votes
4 answers

Location of parenthesis for auto-executing anonymous JavaScript functions?

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed. The code used to wrap an anonymous function in parenthesis and then…
Kevin Hakanson
  • 38,937
  • 23
  • 119
  • 148
100
votes
6 answers

What is this JavaScript pattern called and why is it used?

I'm studying THREE.js and noticed a pattern where functions are defined like so: var foo = ( function () { var bar = new Bar(); return function ( ) { //actual logic using bar from above. //return result; …
Patrick Klug
  • 13,181
  • 13
  • 70
  • 114
85
votes
6 answers

In JavaScript, what is the advantage of !function(){}() over (function () {})()?

Possible Duplicate: What does the exclamation mark do before the function? I've long used the following for self-executing, anonymous functions in JavaScript: (function () { /* magic happens */ })() Lately, I've started seeing more instances of…
Andrew Hedges
  • 21,058
  • 16
  • 62
  • 78
58
votes
4 answers

Defining and calling function in one step

Is there a way in Javascript to define a function and immediately call it, in a way that allows it to be reused? I know you can do one-off anonymous functions: (function(i) { var product = i * i; console.log(product); // Can't recurse…
quis
  • 824
  • 1
  • 7
  • 13
57
votes
7 answers

What is this practice called in JavaScript?

When you wrap your JavaScript code in a function like this: (function(){ var field = ...; function doSomthing(){... ... })(); I noticed that this fixes scoping problems for me on a lot of web pages. What is this practice called?
stevebot
  • 21,481
  • 26
  • 107
  • 176
42
votes
9 answers

self executing function jquery vs javascript difference

What are the difference among - First :- (function () { var Book = 'hello'; }()); Second:- (function () { var Book = 'hello'; })(); First and second are similar some how in work.. Third :- (function ($) { var Book =…
Javascript Coder
  • 5,209
  • 7
  • 38
  • 82
39
votes
5 answers

Dollar sign before self declaring anonymous function in JavaScript?

What is the difference between these two: $(function () { // do stuff }); AND (function () { // do stuff })();
xil3
  • 16,020
  • 8
  • 56
  • 95
30
votes
2 answers

Why use NOT operator on anonymous function call? (a la Knockout 2.1.0)

Possible Duplicate: What does the exclamation mark do before the function? If you look at the source code for KnockoutJS 2.1.0 you will see a code structure like this start on line 7: !function(factory) { ... }(factoryDefinition); The not…
CgodLEY
  • 954
  • 8
  • 16
1
2 3
39 40