IIFE (Immediately Invoked Function Expressions)

IIFE (Immediately Invoked Function Expressions)

·

2 min read

Introduction

In this post, we'll look at what IIFE (pronounced as 'iffy') is, how to define one and what benefits it offers by using them.

What is IFFE?

An IIFE typically looks like this:

//Syntax-1
(function(param){
    //Functional Code
}());

//Syntax-2
(function(param){
    //Functional Code
})();

Let us look at Syntax-1 a little more closer. You can see that the function is declared within a set of parenthesis (surrounding the function) and thus making it an expression and hence the name "function expression". The parenthesis immediately following the closing braces invokes the function immediately and hence the name immediately invoking function expression.

How to create an IIFE?

mohamed-nohassi-odxB5oIG_iA-unsplash.jpg

Let us first look at a simple function 'sayHello()' as shown below:

function sayHello() {
    console.log('Say Hello');
}

This function will output the text 'Say Hello' on the console when invoked by calling the function.

If you want to convert the above function into a IIFE, here is what you need to do:

Step 1:

Remove the function name 'sayHello' and the function turns into an anonymous function.

function() {
    console.log('Say Hello');
}

The anonymous function above will give you an error, since the syntax is not valid. But, we still have not completed defining our IIFE, so don't worry.

Step 2:

Let us add a set of parenthesis to make it a self-invoking function.

function() {
    console.log('Say Hello');
)();

Step 3:

The last step is to wrap the function with another set of parenthesis to make it a fully functional IIFE.

(function() {
    console.log('Say Hello');
}());

Benefits of using IIFE

jeremy-cai-ucYWe5mzTMU-unsplash.jpg

One of the important thing to note while using IIFE is that all variables and functions declared within the IIFE is local to the block and it is not possible for any code outside the block to access them.

In other words, we can say IIFE provides complete encapsulation of variables and functions.

(function() {
    let x = 'Romeo & Juliet';
}());
console.log(x);

The above code will give you an error, since 'x' is not defined.

(function(name1, name2) {
    console.log(name1 + ' & ' + name2);
}("Romeo", "Juliet"));

The above example shows how to pass arguments to an IFFE.

Conclusion

I hope this article gave an overview of what an IIFE is, how to define one and what benefits it offers. Thank you for taking the time to read my article. Do let me know your comments and feedback about the article.

You might also be interested in:

Did you find this article valuable?

Support Skay by becoming a sponsor. Any amount is appreciated!