IIFE in JavaScript

Murtuzaali Surti

• 2 min read

You might be familiar with functions in JavaScript. An IIFE (Immediately Invoked Function Expression) is a special type of function which is invoked implicitly.

Even if you don't invoke it in your code, it will run on it's own. You can relate it with a callback function which is automatically called when a particular event is fired.

(function () {
console.log('IIFE')
})()

You can also define an arrow function as an IIFE.

(() => {
console.log('IIFE')
})()

You might be wondering, well what's the use of this type of function? This same thing can be done like this:

function func(){
console.log('IIFE')
}

func()

Well, here's the catch. When we define a global variable in JavaScript, it can be accessed from anywhere in our code. For example,

var b = 10

function print(){
b = 8
console.log(b) // output: 8
}

print()

console.log(b) // output: 8

In the above code, the value of the variable b is modified from 10 to 8. But what if we don't want to modify the value of the global variable b. What can we do?

One thing we can do is to initialize a new variable b inside the scope of the function print() just like this:

var b = 10

function print(){
let b = 8
console.log(b) // output: 8
}

print()

console.log(b) // output: 10

We were able to create a new variable inside the scope of the function without actually modifying the actual global variable.

But, there's another way! Let's say you don't want to reuse the function print() and also you don't want to create a mess with global variables unintentionally. In that case, you can use an IIFE. Here's how you can do that :

var a = 8;

((a) => {
a = 9; // modifying the copy of 'a'
console.log(a); // output: 9
})(a) // passing a copy of variable as an argument

console.log(a) // output: 8

In the above example, we are passing the value of variable a to the IIFE. Remember that we are only passing a copy of the variable, so we are not actually modifying the global variable. This is most useful when you are dealing with multiple files which are being imported and exported in your project and you don't know the name of every global variable defined.

An IIFE is a function which does it's own thing without affecting things on a global level.

You can also make an IIFE asynchronous.

(async () => {
const get = await fetch(url)
// do something
})()

That was a brief look at IIFE. I hope you got some idea of what's IIFE and how we can use it. If you want to dig deeper, check this out.

Signing off.


How to make a QR Code generator using JavaScript?

Previous

How to compile SASS into CSS and watch for changes?

Next