JavaScript Pills: immediately invoked function expression (IIFE)

Lari Maza
Lari Maza | En
Published in
2 min readOct 10, 2019
Photo by Zoltan Tasi

[clique aqui para português]

This is a post from a series where I share insights from my journey with JavaScript in a mini article format. See all other posts on my profile!

An immediately invoked function expression, or IIFE, is a function called immediately after it is declared.

(function helloWorld() {
alert('Hello, world!');
}
)();
// alert 'Hello, world!'

In the example above, we wrap the function declaration in parentheses and add another pair of parentheses at the end, thus invoking the function immediately. We can also create an IIFE with an anonymous function:

(function() {
alert("What's up?");
}
)();
// alert "What's up?"

As we would when calling any function, we can also use the last pair of parentheses to enter arguments, like the example below:

(function(message) {
alert(message);
}
)("Let's go!");
// alert "Let's go!"

One of the main perks of the IIFE is that it can use its scope to create closure and prevent data inside it from being accessed. In practice, it works like this:

const myFunction = (
function() {
const password = 1337;
return function() {
console.log(password);
}
}
)();
// 1337

The function is executed immediately, as it is an IIFE. It returns an anonymous function, which is stored in myFunction and captures (or focuses) the password variable. This means that it holds the reference to its parent scope, like every nested function does.

Now we have in myFunction a private mutable state that cannot be accessed from outside the function. However, when we do console.log from within the returned function, we can access the password value!

There is also a different syntax for IIFE. We can move the second pair of parentheses into the first pair, thus wrapping the entire expression with the first pair of parentheses:

(function bark() {
alert('Woof!');
} ());

This is just a style choice, as the result is identical.

It is noteworthy that placing these variables in closed scopes not only has its advantages in data security; if fewer variables are created globally, we reduce the noise and chance of conflicting their names.

That’s all for today and see you next time ❤

--

--