JavaScript Immediately Invoked Function Expressions (IIFE)

JavaScript Immediately Invoked Function Expressions (IIFE)

In this article, I am going to discuss JavaScript Immediately Invoked Function Expressions (IIFE) with Examples. Please read our previous article where we discussed JavaScript Anonymous function. At the end of this article, you will understand what are JavaScript Immediately Invoked Function Expressions and when and how to use this in JavaScript.

JavaScript Immediately Invoked Function Expressions:

Sometimes we don’t want to have our function accessible/stored as a variable. We can create an Immediately Invoked Function Expression (IIFE for short). These also called self-executing anonymous functions. They have access to the surrounding scope, but the function itself and any internal variables will not be accessible from outside.

As we have seen in the anonymous function article that another use for anonymous functions is as self-executing functions. A self-executing anonymous function is a function that executes as soon as it’s defined.

An important thing to note about IIFE is that even if we name our function, IIFE cannot be hoisted like standard functions are and cannot be called by the function name they are declared with.

What is IIFE in JavaScript?

An Immediately-invoked Function Expression is a way to execute functions immediately, as soon as they are created. In another way, IIFE is a function expression that immediately invokes after the function definition is complete automatically. The parenthesis () plays an important role in the IIFE pattern. In JavaScript, parenthesis cannot contain statements; it can only contain an expression.

((var foo = 20 >10); // syntax error
(var foo = "foo", bar = "bar"); // syntax error
(20 > 10); // valid
(alert("Hi")); // valid

To turn a normal anonymous function into a self-executing function, we simply cover the anonymous function in parentheses and then add a set of parentheses and a semicolon after it.

Syntax of IIFE:

Syntax of JavaScript Immediately Invoked Function Expressions

IIFEs can be defined with arrow functions as well:

Syntax of IIFE

We can also put the invoking parentheses inside the expression parentheses, there is no difference, It just a styling preference:

Syntax of IIFE in JavaScript

JavaScript IIFE Features:
  • IIFE functions are anonymous functions wrapped in parentheses
  • IIFE functions are called with the parameters immediately after the last parentheses enclosing the anonymous function
  • IIFE functions are immediately invoked as soon as it is created.so cannot be called later
  • IIFE functions take zero or any number of arguments
Use of IIFE in JavaScript:

IIFEs are very useful because they don’t pollute/infect the global object, and they are a simple way to segregate variables declarations. We use it to call a function directly after its definition. So only the name is fancy.

Let’s start from the beginning

Normally, when creating functions, we do something like this which we already learn in the function article:

function sam() {/*func body*/ }
const sam = () => {/* func body*/}

And then in order to execute the code inside, we would need to call this function: sam();

Now, imagine. We call it using its name: sam and a pair of () parenthesis attached to it. What is sam?

It holds a reference to ()=>{ /* function body*/} this code. So then can’t we replace sam with just the reference it holds: ()=>{ /* function body*/} and attach a () to it, to call it? Well, that’s the whole point of that IIFE!

Creating our own IIFE

After all this learning, we got this: ()=> { /*body*/ } ()

But it won’t work, because we missed something little here. This whole piece of code ()=>{} is a whole statement. Not an expression, as it must be in order for it to work. So, we need to convert the statement into an expression. How? let me show you

()=> { /*function body*/ } // statement
(() => {/*function body*/}) //expression

FUNCTON EXPRESSION + () = IIFE

(() => {/*function body*/}) () //IIFE 

So let see our previously created normal named function sam()

function sam() {/*func body*/ } //statement
(function sam() {/*func body*/ }) //expression
void function sam() {/*func body*/ } //expression
! function sam() {/*func body*/ } //expression
+ function sam() {/*func body*/ } //expression

Putting almost any type of operator before the function keyword will convert it from a statement to an expression. And after that to form an IIFE, just add () to the expression. In those () we can pass arguments too.

Example1:
<html>
<head>
    <title>JavaScript IIFE example1</title>
</head>
<body>
    <script>
        (function (a) { 
            console.log(a) 
        })('It is working')//log it is working
    </script>
</body>
</html>

Output: It is working

It displays “it is working” message in the browser console.

Example2:
<html>
<head>
    <title>JavaScrip IIFE example2</title>
</head>
<body>
    <script>
        var myVariable = "I am outside the function.";
        (function () {
            var myVariable = "I am in this anonymous function";
            document.write(myVariable);
        })();
        document.write('<br/>' + myVariable);
    </script>
</body>
</html>

Output:

JavaScript Immediately Invoked Function Expressions Examples

Function declarations want a name, while function expressions do not require it. In order to create IIFE, first of all, define a function expression

Example: IIFE
var sampleIIFE = function () {
            //js code goes here
        };

Now, wrap it with parenthesis. However, parenthesis does not allow declaration. So just remove the declaration part and just write the anonymous function as below.

Example: IIFE
(function () {
               //js code goes here
            });

Now, use the () operator to call this anonymous function immediately after completion of its definition.

Example: IIFE
(function () {
            //js code goes here
        })();

Notice that the closing parenthesis before the semicolon was moved and placed right after the closing curly bracket.

We can easily pass parameters into an IIFE
<html>
<head>
    <title>JavaScript IIFE with parameters example</title>
</head>
<body>
    <script>
        (function (message) {
            alert(message);
        }("Hello World!"));
    </script>
</body>
</html>

Output:

JavaScript Immediately Invoked Function Expressions Examples

Additionally, we can return values to the surrounding scope
<html>
<head>
    <title>JavaScript IIFE return values to the surrounding scope example</title>
</head>
<body>
    <script>
        var example = (function () {
            return 42;
        }());
        console.log(example); // => 42
    </script>
</body>
</html>

Output: 42

Named IIFE

If required it is possible to name an IIFE. While less often seen, this pattern has several advantages, such as providing a reference which can be used for recursion and can make debugging simpler as the name is included in the call stack.

Example: Named IIFE
<html>
<head>
    <title>JavaScript named IIFE example</title>
</head>
<body>
    <script>
        (function namedIIFE() {
            throw error; // We can now see the error thrown in 'namedIIFE()'
        }());
    </script>
</body>
</html>

Output:

IIFE Examples in JavaScript

While wrapping a function in parenthesis is the most common way to denote to the JavaScript parser to expect an expression, in places where an expression is already expected, the notation can be made more concise.

Example: JavaScript IIFE wrapping a function into parenthesis
<html>
<head>
    <title>JavaScript IIFE wrapping a function into parenthesis example</title>
</head>
<body>
    <script>
        var a = function () { return 42 }();
        console.log(a) // => 42
    </script>
</body>
</html>

Output: 42

We can write all the functions and variables inside IIFE without worrying about polluting the global scope or conflict with other’s JavaScript code which has functions or variables with the same name. To solve this problem, wrap all the code in Script1.js & Script2.js file in IIFE as shown below.

Example: IIFE Script1.js
(function () {
            var userName = "Shagufta";

            function display(name) {
                alert("Script2.js: " + name);
            }

            display(userName);
        })();

 

So, even if Script1.js & Script2.js file includes functions and variables with the same name, they won’t conflict with each other and pollute the global scope. Also, we can pass arguments in IIFE as shown below.

Example: IIFE Script2.js
var userName = "JavaScript";

        (function (name) {

            function display(name) {
                alert("Script2.js: " + name);
            }

            display(name);
        })(userName);
IIFEs starting with a semicolon

We might have seen semicolon before IIFE while creating IIFE

;(function () {
                /*func body*/
})()

This is used to prevents issues when concatenating two or more JavaScript files. Since JavaScript does not require semicolons, it is optional.

Let’s understand with an example:

If we concatenate two files with self-invoking functions together that looks like this:

File First: (function () {/*…First…*/})()

File Second: (function () {/*…Second…*/})()

File First + Second: (function () {/*…First…*/})() (function () {/*…Second…*/})()

We have two statements without a separator. This happens when we concatenate(combine) files together and then minify them. Now the programmer of file second puts a semicolon in front:

File Second: ;(function () {/*…Second…*/})()

And then we will get a working script of IIFE (function () {/*…First…*/ })();(function () {/*…Second…*/})()

Advantages of IIFE:
  1. IIFE does not create unnecessary global variables and functions.
  2. Functions and variables created in IIFE do not conflict with other functions & variables even if they have the same name.
  3. Organize JavaScript code.
  4. Make JavaScript code maintainable
  5. The benefit of using self-executing anonymous functions is that the variables we create inside of them are destroyed when the function exits. In this way, we can avoid conflicts between variable names, and we avoid holding variables in memory after they’re no longer needed.

In the next article, I am going to discuss JavaScript Array Function with Examples. Here, in this article, I try to explain JavaScript Immediately Invoked Function Expressions with examples. I hope this JavaScript Immediately Invoked Function Expressions article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this JavaScript Immediately Invoked Function Expressions article.

Leave a Reply

Your email address will not be published. Required fields are marked *