IIFE (Immediately invoked Function Expression)

IIFE (Immediately invoked Function Expression)

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

What does it actually mean?
So, IIFE is a design pattern to write functions in JavaScript which runs as soon as we define the function.
In regular functions like function declaration or function expression, we can call that function at any place we want, after defining it. And that takes the name of the function and the expression to invoke it.

(function () {
  /* your code here */
})();


IIFE is also known as Self-Executing Anonymous Function. Because as the name suggests it is a anonymous function which has no name associated with it and it executes by itself.

IFFE contains two major parts:

  1. First is the anonymous function wrapped inside parenthesis which is called Grouping Operater ( ). By that IIFE encloses itself within the lexical scope, that prevents accessing variables outside the function.
  2. Second part creates the immediately invoke function expression ( ). Which is defined after the function wrapped inside Grouping Operator.

A lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration. But the opposite is not true.

Why IIFE is useful?

Avoid polluting the global scope

If we have some piece of code that we will only use once, using IIFE will be a good choice. Because the variables defined inside the function will only be declared after the function is executed.
So, that way we won't be polluting our global scope with unnecessary variables and function that has only one time use.
Because we won't be reusing that code piece again, IIFE is a better option than function declaration or function expression.

(function(){
  //some initiation code 
  let firstVariable;
  let secondVariable;
})();
// firstVariable and secondVariable will be declared after the function is executed.

Execute an async function

With the help of IIFE, we can use Async and Await inside the useEffect. And also it can be used in older browsers and JavaScript runtimes that have no top-level-await declaration.

useEffect(() => {
  (async() => {
      const response = await axios.get('/api/users');
      console.log(response.data.users);
  });
}, []);


I'm sure this concise blog helped you dust off your IIFE knowledge in some way.
I've covered few more JavaScript topics before, do check them out.

Happy coding . . .

I would ❤ to connect with you at Twitter | LinkedIn | GitHub

Share your appreciation and queries in the comments section below.