DEV Community

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

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.