markdown guide
 

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
    })
})()
 
 

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.

 

Nice approach with food πŸ˜‹. Thanks for thΓ© explanation.

 
 

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!!


`

 

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

 

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

I 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 an extra set of parentheses - so that's what the 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.

 
 

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.

 

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.

 

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

Classic DEV Post from Jan 8

Jenn's Guide to Thriving in Tech

General tips for those in tech careers.

Latheresienne profile image
I am a passionate problem solver no matter what the challenge is.