DEV Community

Cover image for IIFE(immediately-Invoked function Expression)
Hamza Ali
Hamza Ali

Posted on

IIFE(immediately-Invoked function Expression)

  • The term immediately-Invoked function Expression was tossed by BEN ALMAN in his blog. Before that it was referred to as self-executing anonymous function. As the name suggests it is a kind of JavaScript function which gets executed immediately after its declaration.

  • A normal JavaScript function can be declared by one of these methods

//First method
function foo(){ //code }

//second method 

const foo = function (){//code}
//both of these functon can be invoked by putting the pranthesis after their name

foo()
// This will invoke the function and will cause its execution
Enter fullscreen mode Exit fullscreen mode

But what if we want to invoke a function right after its declaration? JavaScript doesn't allow putting parenthesis after a function declaration

function foo(){//code}()
// This will throw syntex error same goes for the other mehtod
const foo = function (){//code}()

//But if we pass argument to the paranthesis after the function declaration no exception will occuer

function foo(){//code}(0)

// This will not throw any exception because JavaScript treets this piece of code in different way

function foo(){//code}

(0)

//This is how JavaScript treets this piece of code.
Enter fullscreen mode Exit fullscreen mode

So we know that JavaScript doesn’t throw errors when we pass some argument to the parenthesis. So to create an IIFE we will pass our function as an argument to the parenthesis and after the parenthesis, we will add another parenthesis to invoke the function that we just passed.

(function(){//code})()
Enter fullscreen mode Exit fullscreen mode

Use cases

  • Avoid polluting namespace

As our application gets big the need of we want to avoid duplicating the names of our variables to avoid confusion. In case when we know that a piece of code will only execute once we can use IIFE.

(function(){
//code
let veriable1
let veriable2
//code
})()

//As soon as this IIFE gets executed the veriable1 and veriable2 will be discarded and will
//be available to you later in the file
Enter fullscreen mode Exit fullscreen mode
  • Privacy

we can use IIFE to create private and public variables and methods.

const canYouSeeMe = () =>
    (() => {
        let privateVariable = 5;
        function iamHidden() {
            console.log("haha YOU can't see me");
        }
        return {
            youCanSeeMe() {
                console.log('you can see me');
            }
        };
    })();

const hideSeek = canYouSeeMe();

console.log(hideSeek.youCanSeeMe()); // This will print out "you can see me"
console.log(hideSeek.iamHidden()); // undefined, because this method is private
console.log(hideSeek.privateVariable); // undefined, because this veriable is private
Enter fullscreen mode Exit fullscreen mode
  • Closure

    Before the introduction of let and const in ES6 and block scope. With the var, we only have function and global scope.

    Let’s take a scenario

    const buttons = document.getElementsByClassName('className');
    for (var i=0;i<6;i++){
        buttons[i].addEventListener('click',function(e){
        e.preventDefault()
        console.log(`I am button number ${i}`)
    })
    }
    
    //what do you think the output of the button click will be.
    // If the button is clicked after the execution of the loop all of the six buttons
    // will print out "I am button number 6". Because at the end of the execution of the loop
    // the value of i is 6.
    

to encounter this before ES6 IIFE was used

const buttons = document.getElementsByClassName('className');
            for (var i = 0; i < 6; i++) {
                ((index) => {
                    buttons[index].addEventListener('click', function (e) {
                        e.preventDefault();
                        console.log(`I am button number ${index}`);
                    });
                })(i);
            }

// This execution will get you your desired result because of clouser
Enter fullscreen mode Exit fullscreen mode

That's it from this post

If you have any suggestions please leave them in the comments

Top comments (1)

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍