DEV Community

Latheresienne
Latheresienne

Posted on

Explain IIFE(Immediately Invoke Function Expression) Like I'm Five

Top comments (16)

Collapse
 
shiling profile image
Shi Ling

Analogy:

IIFE
Ask friend for the WIFI password, use it immediately, forget about the password afterward.

Normal Function
Ask friend for the WIFI password, writes it on a piece of paper, paste on the wall, everyone knows it.

What's the point of IIFE?

The IIFE is a javascript design pattern invented in the days before modules was introduced in ES6, and people wanted to run a piece of code only once, like a setup code, without polluting the global namespace.

e.g.

(function(){

    // some code you just want to run only once, e.g. setup Vue js.
    var app = new Vue({
        el: "#main",
        //... more stuff
    })
})()
Collapse
 
latheresienne profile image
Latheresienne

Thanks for the explanation😃

Collapse
 
nestedsoftware profile image
Nested Software • Edited

Normally we create a function, then call it later on:

function hello(name) {
  console.log("hi there, " + name + "!")
}

hello("Lisa") // > hi there, Lisa!

It turns out we can also call a function immediately following its definition:

(function hello(name) {
  console.log("hi there, " + name + "!")
})("Jennifer") // > hi there, Jennifer!

hello("Tom") // > Uncaught ReferenceError: hello is not defined

In the above code sample, we define the function hello and call it immediately, passing in "Jennifer" as a parameter. It seems JavaScript can't properly parse this unless the function definition is wrapped in parentheses - so that's what those extra parentheses are for.

This type of self-calling function, an IIFE, executes once and that's it. You can't call it separately - note the function is not visible when we try hello(“Tom”). The name of the function can also be omitted. You'll often see IIFEs in this anonymous form:

(function (name) {
  console.log("hi there, " + name + "!")
})("Jennifer") // > hi there, Jennifer!

IIFEs were used in the old days of JavaScript, mostly to create namespaces - the code inside the IIFE is isolated from the outside world, none of its variables can be seen from outside the IIFE (though global variables are still visible from within the IIFE). This means variables that are defined inside the IIFE won't accidentally clobber any global ones that have the same name. That's what it means when people say the IIFE does not "pollute" the global namespace. This way only the return values from such a function are available for use.

I don't think you'd see this kind of thing so much anymore these days, since JavaScript supports modules natively with the import syntax nowadays.

Collapse
 
latheresienne profile image
Latheresienne

Thanks for the explanation.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀 • Edited

A more recent use of iife is to use async await.

;(async () => {
   const myDataResponse = await fetchData("https://example.com/some-api.json");
})();

The above changes the context of the block (the function body) to mean I can use await to grab data that may take some time to retrieve.

Collapse
 
codefinity profile image
Manav Misra

twitter.com/GoCodeFinity/status/12... This is great, as I just was wondering (via Twitter b4 seeing this) about my pattern that is very similar to yours.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

It's not wired at all, as your tweet asks. It's just a workaround until top-level await comes in circa 2020. In the mean time I always include a semicolon Infront so the interpreter doesn't think that any preceding thing is a function call. You should do the same. 👽

Thread Thread
 
codefinity profile image
Manav Misra

Tx. 'weird' not 'wired' 👆🏽;)

Thread Thread
 
adam_cyclones profile image
Adam Crockett 🌀

I use a phone exclusively on Dev.to

Collapse
 
owenconti profile image
Owen Conti 🇨🇦 • Edited

IIFE:

An item you put on your to-do list and then do right away.

Normal function:

An item you put on your to-do list and you'll get to it later.


An IIFE is nothing more than a function that is called once and it's called right away.

They used to be big back in the day to avoid variable scoping issues:

// app.js

var secret = '123';

The above secret variable is in the window scope, so it is accessible anywhere in the runtime. Changing to use an IIFE, it put the variable in the function's scope, meaning it cannot be accessed outside the function:

// app.js

(function() {
   var secret = '123';
})();

// I can't see `secret` down here!!


`

Collapse
 
latheresienne profile image
Latheresienne

Thanks for the explanation. Your approach with a to-do list is just great!

Collapse
 
cookrdan profile image
Dan • Edited

IIFE:
Plate goes on the table and a fork full of food immediately goes into your mouth.

Normal Function:
Plate goes on the table and you must wait until Mom tells you to each fork full.


IIFEs are functions that are run immediately without the need to be called from somewhere else.

Normal functions need to be called before they are run.

Collapse
 
latheresienne profile image
Latheresienne

Nice approach with food 😋. Thanks for thé explanation.

Collapse
 
cookrdan profile image
Dan

You’re welcome

Collapse
 
guitarino profile image
Kirill Shestakov

No IIFE: I buy food, we eat, then leave the dishes on the table.

IIFE: I buy food, we eat, then toss out the leftovers and put the dishes away.

Collapse
 
wiltel492019 profile image
Wiltel492019

I understand your function logic. Gitter done!!! Well spoken!!!