Categories
iife javascript

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

917

I would like to know what this means:

(function () {

})();

Is this basically saying document.onload?

6

960

It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created.

It has nothing to do with any event-handler for any events (such as document.onload).
Consider the part within the first pair of parentheses: (function(){})();….it is a regular function expression. Then look at the last pair (function(){})();, this is normally added to an expression to call a function; in this case, our prior expression.

This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.
This is why, maybe, you confused this construction with an event-handler for window.onload, because it’s often used as this:

(function(){
  // all your code here
  var foo = function() {};
  window.onload = foo;
  // ...
})();
// foo is unreachable here (it’s undefined)

Correction suggested by Guffa:

The function is executed right after it’s created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn’t automatically mean that it’s executed, if for example the IIFE is inside a function then it won’t be executed until the function is called.

Update
Since this is a pretty popular topic, it’s worth mentioning that IIFE’s can also be written with ES6’s arrow function (like Gajus has pointed out in a comment) :

((foo) => {
 // do something with foo here foo
})('foo value')

6

  • 1

    @gion_13 what is the difference between the creation phase and parse phase?

    Mar 28, 2016 at 18:31

  • 2

    @jlei the way I see it, a js program’s life cycle includes the following phases: parsing, creation/compilation, execution. Although the actual implementation (and naming :)) ) may differ from browser to browser, we can determine these phases in our code by watching out for parsing errors, hoisting and run time errors. I personally haven’t found many resources on this because it’s too low level and it’s not something that the programmer can control. You can find some sort of explanation in this SO post: stackoverflow.com/a/34562772/491075

    – gion_13

    Mar 29, 2016 at 5:45

  • @sam firat of all, there’s the varianle declaration and the new keyword. This means that in your example you are instantiating a new obiect defined by it’s constructor (anonymous function expression) and it’s invoked via the new operator, not by calling the finction as in the IIFE example. Sure that function acts like a closure for it’s contents but It’s by far a different use case.

    – gion_13

    Jan 30, 2017 at 6:13

  • 1

    @Pankaj — Taken by itself, that is not even syntactically valid JS (it is a function expression but not in expression context so is treated as a syntax error).

    – Quentin

    Oct 9, 2018 at 10:46

  • 1

    it’s important to note that IFFE’s were useful because of the var keyword, which was global scoped. Therefore JS developers had to find a way to ‘limit’ variables in their code.

    Oct 8, 2021 at 14:07

123

It’s just an anonymous function that is executed right after it’s created.

It’s just as if you assigned it to a variable, and used it right after, only without the variable:

var f = function () {
};
f();

In jQuery there is a similar construct that you might be thinking of:

$(function(){
});

That is the short form of binding the ready event:

$(document).ready(function(){
});

But the above two constructs are not IIFEs.

7

  • 90

    The last two aren’t really IIFEs, since they’re invoked when the DOM is ready and not immediately

    – svvac

    May 22, 2014 at 11:48

  • 18

    @swordofpain: Yes, that is correct, they are not IIFEs.

    – Guffa

    May 22, 2014 at 17:04

  • @swordofpain considering the second snippet; would there be any value in add () to the end of the function by turning it into an IIFE?

    Jul 25, 2015 at 13:53

  • Is the semicolon at the end necessary?

    – FrenkyB

    Mar 31, 2017 at 12:09

  • @FrenkyB Not necessary, no, but encouraged (semicolons are frequently not actually necessary in Javascript, but it’s good practice). Each of those are statements that happen to include anonymous functions, rather than being function declarations.

    – Ledivin

    Jun 20, 2017 at 17:41


64

An immediately-invoked function expression (IIFE) immediately calls a function. This simply means that the function is executed immediately after the completion of the definition.

Three more common wordings:

// Crockford's preference - parens on the inside
(function() {
  console.log('Welcome to the Internet. Please follow me.');
}());

//The OPs example, parentheses on the outside
(function() {
  console.log('Welcome to the Internet. Please follow me.');
})();

//Using the exclamation mark operator
//https://stackoverflow.com/a/5654929/1175496
!function() {
  console.log('Welcome to the Internet. Please follow me.');
}();

If there are no special requirements for its return value, then we can write:

!function(){}();  // => true
~function(){}(); // => -1
+function(){}(); // => NaN
-function(){}();  // => NaN

Alternatively, it can be:

~(function(){})();
void function(){}();
true && function(){ /* code */ }();
15.0, function(){ /* code */ }();

You can even write:

new function(){ /* code */ }
31.new function(){ /* code */ }() //If no parameters, the last () is not required

8

  • 4

    last one 31.new‘ is invalid syntax

    – cat

    Mar 1, 2016 at 2:39


  • 10

    Why are there so many ways to write the same thing?!! >_< I don’t like this language

    Jun 23, 2016 at 14:33

  • 8

    aaand the winner is ;(function(){}());

    Mar 27, 2017 at 23:45


  • 1

    @Awesome_girl: It’s not that there are many ways to write the same thing; it’s that JS has a loose type system with operators that can operate on any value type. You can do 1 - 1 and you can just as easily do true - function(){}. It’s only one thing (an infix subtraction operator) but with different, even nonsensical operands.

    – user9274775

    Feb 3, 2018 at 18:37


  • 1

    Whats the benefit of using Crockford’s function (function(){}()) over the others?

    May 7, 2018 at 15:47