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.varapp=newVue({el:"#main",//... more stuff})})()
Normally we create a function, then call it later on:
functionhello(name){console.log("hi there, "+name+"!")}hello("Lisa")// > hi there, Lisa!
It turns out we can also call a function immediately following its definition:
(functionhello(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.
How’s it going, I'm a Adam, a Full-Stack Engineer, actively searching for work. I'm all about JavaScript. And Frontend but don't let that fool you - I've also got some serious Backend skills.
Location
City of Bath, UK 🇬🇧
Education
10 plus years* active enterprise development experience and a Fine art degree 🎨
I'm a JS Subject Matter Expert (SME) that has spent the past few years spearheading curricula and teaching initiatives at colleges and bootcamps, in person and virtually.
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.
How’s it going, I'm a Adam, a Full-Stack Engineer, actively searching for work. I'm all about JavaScript. And Frontend but don't let that fool you - I've also got some serious Backend skills.
Location
City of Bath, UK 🇬🇧
Education
10 plus years* active enterprise development experience and a Fine art degree 🎨
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. 👽
I'm a JS Subject Matter Expert (SME) that has spent the past few years spearheading curricula and teaching initiatives at colleges and bootcamps, in person and virtually.
How’s it going, I'm a Adam, a Full-Stack Engineer, actively searching for work. I'm all about JavaScript. And Frontend but don't let that fool you - I've also got some serious Backend skills.
Location
City of Bath, UK 🇬🇧
Education
10 plus years* active enterprise development experience and a Fine art degree 🎨
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.jsvarsecret='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(){varsecret='123';})();// I can't see `secret` down here!!
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.
Thanks for the explanation😃
Normally we create a function, then call it later on:
It turns out we can also call a function immediately following its definition:
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: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.
Thanks for the explanation.
A more recent use of iife is to use async await.
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.
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.
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. 👽
Tx. 'weird' not 'wired' 👆🏽;)
I use a phone exclusively on Dev.to
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:
The above
secret
variable is in thewindow
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:`
Thanks for the explanation. Your approach with a to-do list is just great!
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.
You’re welcome
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!!!