Write your answer…

An immediately invoked function expression, as you might have inferred, is a function that is called immediately after it is defined; immediately here means before a semicolon (or implied semicolon) would occur.

IIFEs look like this:

(function() {
  // Do something
})();

IIFEs are useful because they enclose the logic inside the function into a new scope (i.e. a closure). This prevents the logic inside the function from polluting the global namespace and allows variable names to be reused. They can also be used to hide other functions and variables, effectively making them private.

You will see module systems like AMD and UMD use IIFEs a lot to isolate modules from the outside. Dependencies that a module imports can be passed into the IIFE as arguments.

I personally will also occasionally use IIFEs in scenarios where I am not otherwise able to declare a block of code as async. Example:

(async function() {
  const data = await fetch(url);
})();
Clap3
Spot On2
Show all replies

In reply to Mark above, I believe it could be changed to a fat arrow call, to keep scope to the calling class/object.

(async () => {})(); Allowing you to access any object/class fields from within the method.

Reply to this…

Hashnode is building a friendly and inclusive dev community. Come jump on the bandwagon!

  • 💬 A beginner friendly place

  • 🧠 Stay in the loop and grow your knowledge

  • 🍕 >500K developers share programming wisdom here

  • ❤️ Support the growing dev community!

Register ( 500k+ developers strong 👊)

Matt Strom gave an EXCELLENT answer. It opens the door to some other possibilities as well.

They can also let you shorthand commonly used properties to save bandwidth -- again without polluting the global scope. Google uses this with both document and window in many of their scripts (including adsense).

(function(d,w) {
})(document, window);

That way you aren't typing "document.getElementByWhatever" a few dozen times, you can just "d."

Strangely enough because it puts the references to "d" and "w" into the local scope, it ends up speeding up code that refers to document and window frequently as it moves them up the food chain in the variable search order for the interpreter.

It's also handy for mixing "use strict" with non-strict code as you can "use strict' inside the IIFE without it applying to the rest of the file.

VERY handy all-around... though as Matt's post implies, the big feature is scope isolation.