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.
645 questions
-1
votes
1 answer

Scope of a named IIFE name

I thought I understood the nature of Immediately Invoked Function Expressions (IIFEs), but now I realise I don't. I created an IIFE in a piece of code (in a web page using JQuery as it happens). However if I name the function, and try to call that…
Incans
  • 182
  • 9
-1
votes
1 answer

Why Mozilla put Object.assign polyfill in an anonymous function?

I have a question. In the Polyfill section of MDN page for Object.assign function. The technical writers in Mozilla put a polyfill of Object.assign in an anonymous function: if (typeof Object.assign != 'function') { (function () { …
Huy Tran
  • 815
  • 1
  • 12
  • 22
-1
votes
1 answer

Immediately Invoked Function Expression use case:inadvertent sharing via closures

var result=[]; for(var i=0;i<5;i++){ result.push(function () {return i}); } console.log(result[1]()); //5 not 1 I think the result should be [0,1,2,3,4] and I don't understand why the value should be 5. How does it work? I am completely confused.
Zoe
  • 1
  • 1
-2
votes
1 answer

Can anybody explain what is going on here in terms of type coercion, IIFE, and closures?

can anyone explain to me what is JS doing here? Can anybody explain what is going on here in terms of type coercion, IIFE, and closures? Function.prototype.toString = ( function() { const toStringFnRef = Function.prototype.toString; …
-2
votes
2 answers

Why is TypeScript generating an IIFE for a namespace?

I have this TS code: export namespace Constants { export var x = 0; } If I compile it with 'tsc' I get this JS code: "use strict"; exports.__esModule = true; exports.Constants = void 0; var Constants; (function (Constants) { …
Alter Ego
  • 13
  • 1
  • 4
-2
votes
1 answer

construct object in realtime with IIFE as method

when i want that the property get year to print, i cant acces to the variable I have this obj: let human = { birdYear: 1, getAge: (function (birdYear) { return 2021 - this.birdYear })() }; when print human get this: Cannot read property…
Nube Nube
  • 47
  • 5
-2
votes
2 answers

Can someone explain Javascript classic module pattern and why we would use it?

I came across this code, which I don't understand what is going on, and then I removed the IIFE parenthesis and the console.log didn't work anymore, can someone explain what is going on, It is called the classic module pattern. Why we want to use…
Jason
  • 67
  • 7
-2
votes
1 answer

IIFE vs function call (with parameters), inside a loop

I am confused between using an IIFE vs using a normal function call (with parameters) inside a for loop. Lets say the function is - function print_doc_count(i){ var str= "collection" + i.toString(); db.collection(str).count(function(err,…
vjjj
  • 1,019
  • 3
  • 10
  • 35
-2
votes
2 answers

Javascript IIFE - back door?

There anyone try or know how to get acces to variable in anonymous function?? Example var test = "Hi"; (function() { var test = "Bye"; // Outputs "Bye" console.log(test); })(); // Outputs "Hi" console.log(test); As you can see last…
-2
votes
1 answer

How to using ES6 Arrow function to realize Immediately-Invoked Function Expression (IIFE))?

How to using ES6 Arrow function to realize IIFEImmediately-Invoked Function Expression? Here is my demo codes, and it had tested passed! // ES 6 + IIFE (() => { let b = false; console.log(`b === ${b}!`); const print = `print()`; …
-2
votes
1 answer

Wrap ALL Javascript code in an IIFE

Is it possible to wrap all your Javascript code, no matter how long it is, in an Immediately Invoked Function Expression (IIFE)? If yes, what are the potential pros and cons?
GiS91
  • 175
  • 1
  • 4
  • 12
-3
votes
1 answer

The purpose of (function(){})() in javascript

What's the purpose of doing (function(){ console.log('holla at world'); })(); instead of console.log('holla at world'); Is there an example where something has to be done using the first case.
User314159
  • 7,733
  • 9
  • 39
  • 63
-3
votes
3 answers

Manually Invoke IIFE

I've got a library (Hubspot Odometer) which I am using in a web application I am developing and it works fine to create and run Odometer style widgets on a page. The trouble is that they are part of a dashboard interface which has panes that are…
Daniel Waghorn
  • 2,997
  • 2
  • 20
  • 33
-4
votes
1 answer

Why IIFE can fix "cannot set property 'onclick' of null"

I have a block of code as the following

Matching Game

Click on the extra smile face on the left