What is IIFE?
So what even is IIFE?
But why do you need the wrapper of a function? Can't you just put the code just as is inside?
But... Take an example of setting
When you wrap all of that in an IIFE, however, the return value is contained inside the IIFE, and the returnn value will only be the return value of the IIFE itself, which is empty air.
Nice. But that's not the main reason why people use IIFEs in everyday
society websites. The most important reason is...
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).
That in turn means that the variables that you define inside your code, using
var, will all be scoped just to the code block of the IIFE.
const are block-scoped, meaning that they'll be containned in any block (including
var is function- or global-scoped, which here means that it will be contained innside the IIFE, which is a function. This can extremely useful for browser ennviroments, in which you might wannt scripts to run independently without interefering with each other.
Please use IIFEs whenn you want to contain variables into a script (e.g. a browser context, runninng lots of
<script>s on a single page or omit the return value in order to prevent annoying browser behavior.
That's all for this article - thanks for reading!