JavaScript: Understanding IIFE

IIFE is a widely used technique to create function scope for particular lines of code that require some privacy instead of writing everything in the global scope.

Image for post
Image for post

In the above example, It is clear that Andy and Mary need some privacy. So they decide to wrap their details with a function and tell the outer world only what they need to know.

This made things better but still, they do not want everyone to knock at their doors by invoking the globally exposed AndyMaryHouse function. So, they turned their function declaration into an IIFE.

They wrapped their function with a Grouping operator and invoked immediately after that.

So the IIFE allowed them to live as they used to (in the global execution flow) but with their private information intact. They lived happily ever after.

A grouping operator is necessary to make the IIFE work. Or else, the JavaScript interprets the invocation () as an empty grouping operator followed by a perfectly OK function declaration and throws SyntaxError: Unexpected token ‘)’.

We can also have the invocation braces after closing the grouping operator. And for the arrow functions, the invocation should be outside the grouping operator.

The introduction of operators like + and ! keeps JavaScript from complaining about the dangling empty grouping operators in the syntax.

  1. Put the logic inside a function.
  2. Wrap the function with a grouping operator.
  3. Invoke the expression immediately.

The privacy problem expressed in the Andy-Mary example can be solved even more precisely by using block-scoped variables. In the below example, the privateParts array is not even visible in the outer block scope (House).

But still, IIFE has its other use cases as discussed in this post. It talks about IIFEs in the closure, Aliasing Variables, Optimization through minification, and some more.

Thank you.

Written by

Full Stack Developer. JavaScript, React, Node, GraphQL.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store