IIFE (Immediately Invoked Function Expression) in Javascript

IIFE’s full form goes like Immediately Invoked Function Expression & it means the function is invoked at the same place where it is defined.

Syntax of IIFE in Javascript

(function (){
    //performing operations
})()

From the above syntax, we can interpret that an anonymous function is created and then it is enclosed by round brackets, finally this function is called using ().

Therefore IIFE can help to decrease name collisions because it creates an anonymous function. Along with this IIFE deals with memory inefficiency caused by declaring global variables & objects.

Let us see an example where IIFE is called globally. Inside the function an array is passed & the function returns its sum and the answer is stored in the array_sum variable.

Code:

let array_sum = (function (arr){
    let sum=0;
    for(let i=0;i<arr.length;i++){
        sum+=arr[i];
    }
    return sum;
})([1,2,3,4,5])
console.log(array_sum);

Output:

15

You can also use an arrow function to create IIFE in Javascript. Also named IIFE can also be created by giving a name to the function but it cannot be used again. Therefore it is recommended to avoid creating named IIFE.

Creating async IIFE

Writing an async IIFE gives the permission to use await and for-await in javascript. Here is an example of the same.

const gettingFileData = async (url) => {
    // performing operations
};
(async () => {
    const alldata = await         gettingFileData("https://filepath/mainfile.txt");
    for await (const smallerdata of alldata) {
    console.log({ smallerdata });
}
})();

Why sometimes IIFE starts with ; (semicolon)?

You might see some IIFE starting with ; in some code files the reason for this is semicolon terminates the code present before an IIFE.

If there are two code files that concatenate and both of them contain only IIFE in the code then the javascript compiler will give a runtime error. So semicolon (;) is necessary to separate them.

Here is an example of code that needs to be avoided when combining 2 code files.

(()=>{
    // This IIFE was present inside file 1
})()

(()=>{
    // This IIFE was present inside file 2
})()

I hope you understood the basics of IIFE through this blog. Feel free to ask your doubts and share your thoughts in the comment box.