In this tutorial, you will learn about JavaScript immediately invoked function expressions (IIFE).

TL;DR

A JavaScript immediately invoked function expression is a function defined as an expression and executed immediately after creation. The following shows the syntax of defining an immediately invoked function expression:

(function(){
    //...
})();

Why IIFEs

When you define a function, the JavaScript engine adds the function to the global object. See the following example:

function add(a,b) {
    return a + b;
}

On the Web Browsers, the add() function is added to the window object:

console.log(window.add);

Similarly, if you declare a variable outside of a function, the JavaScript engine also adds the variable to the global object:

var counter = 10;
console.log(window.counter); // 10

If you have many global variables and functions, the JavaScript engine will only release the memory allocated for them until when the global object loses the scope.

As a result, the script may use the memory inefficiently. On top of that, having global variables and functions will likely cause the name collisions.

One way to prevent the functions and variables from polluting the global object is to use immediately invoked function expressions.

In JavaScript, you can have the following expressions:

'This is a string';
(10+20);

This syntax is correct even though the expressions have no effect. A function can be also declared as an expression which is called a function expression:

let add = function(a, b) {
    return a + b;
}

In this syntax, the part on the right side of the assignment operator(=) is a function expression. Because a function is an expression, you can wrap it inside parentheses:

let add = (function(a, b) {
    return a + b;
});

In this example, the add variable is referenced as the anonymous function that adds two arguments.

In addition, you can execute the function immediately after creating it:

let add = (function(a,b){
    return a + b;
})(10, 20);

console.log(add);

In this example, the add variable holds the result of the function call.

#javascript #programming #developer #web-development

JavaScript Immediately Invoked Function Expressions (IIFE) Explained
1.85 GEEK