re: Explain IIFE(Immediately Invoke Function Expression) Like I'm Five VIEW POST

FULL DISCUSSION
 

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.

 
code of conduct - report abuse