Immediately Invoked Function Expression (IIFE) in JavaScript .

Get to know iffy in JS (or refresh your memory in 3 mins :))

The Immediately Invoked Function Expression term sounds very elitist and advanced but truth is it’s very simple.

I’ve prepared some examples for you as well as common traps you might encounter during the job interview.

Getting right to it

The IIFE is a way to execute functions immediately, as soon as they are created. We can do that by enclosing the entire function in brackets, followed by ().

It’s a good way to protect the scope of your function and the variables defined in it. The IIFE creates it’s own scope.

The examples

Basic syntax (note the wrapping parenthesis)

(function() {
/* your work here */
const scopedVariable = "I am available only in this block";
console.log(`You will see me in the console. ${scopedVariable}`);
})()
// or with arrow function(() => {
/* your work here */
const scopedVariable = "I am available only in this block"; console.log(`You will see me in the console. ${scopedVariable}`);
})()

We can amend the syntax a bit.
The () is now inside the expression parenthesis.
Works the same (just keep the codebase consistent).

(function() {
/* still works */
}())

(() => {
/* still works */
}())

We can also give a name to our function — and the function name namedStillScoped does not “leak” to the global namespace.

(function namedStillScoped() {  console.log("puma");})();

I’ve also seen this in the wild:

;(function() {
/* */
})()

This is in fact clever old school trick, as it prevents issues when blindly concatenating two things.

Since JavaScript does not require semicolons, we (or the bundler) might concatenate a bit too much accident. Something like that will crash:

const willCrash = 'Hi there!'(function () {
// note the lack of semicolon after 'Hi There!'
})();

Since linting tools, webpack and so on that is rarely the case.
But still useful to know about it.

The IIFE can accept parameters and return a value

Here we are making use of ES6 default parameters feature as well as we create an object with short syntax.

const person = (function (name = "puma", id = 1) {  return {    id,    name,  }; 
})();
console.log(person);
// { id: 1, name: 'puma' }

The IIFE to create utility variable

We can create object with methods.

<script src="https://cdnurl.com/somelibrary.js"></script>
<script>
const myUtility = (function () {
function createMyUtility() {
// logic here
}
function anotherMyUtilityMethod() {
// logic here
}
return {
createMyUtility,
anotherMyUtilityMethod
}
})();
</script>

We can the use it like so myUtility.createMyUtility().
This is especially useful when we create some plugins or packages and we want to ensure the names are scoped.

The async await usage

You also can do something like this (the example is coming from Node.js environment).
We can’t use await outside of async and that is when IIFE can help us.
The example is of course simplified, just to give you a hint that it’s an option.

(async () => {  try {    await doSomething();  } catch (e) {    console.error(e.stack);    process.exit(1);}})();

A word about let and const

ES6 has introduced let and constfor us.

Both of them use block scope.

With that in mind, we can now limit the variable namespace within curly brackets, without enclosing them within an IIFE function.

In many cases that’s not enough and that is why we should know and understand the IIFE.

The interview scenario

The “tell me about IIFE” is still a very common interview question.
It often comes up with a follow up question i.e. simple snippet:

function foo(){ 
// will I run?
}();

We already know that the syntax is not correct and that it should be one of the below:

(function foo() {
// I will run because of the wrapping parenthesis
})()
// or this(function foo() {
// I will run too
}())

Another question you might get is “why does it return undefined”:

const foo = void (function bar() {
return 'foo';
})();

console.log(foo); // undefined

Now this is a trap because the IIFE will run. Then why does it return undefined?
This comes down to the void keyword, which specifies that function does not return anything. If we remove the void keyword, the IIFE works correctly.

TL;DR

The IIFE in JavaScript:

  • are invoked immediately after creation
  • are great way to protect scope (the IIFE create’s it’s own scope)
  • the syntax of IIFE (remember the wrapping parenthesis and () at the end to call the function
(function() {
/* */
})()

(() => {
/* */
})()

Summary

As we can see, the IIFE in JavaScript is in fact simple yet powerful feature.

It’s definitely worth to have it in the backpocket.

Technical Lead. Seeking to make a change. Doing quality work that matters for people who care.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store