JavaScript: Understanding IIFE

Karthick Ragavendran
2 min readSep 1, 2020

--

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.

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.

The Grouping Operator

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 ‘)’.

IIFE With Arrow Functions

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.

Tricking JavaScript Into Executing IIFEs

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

Take Away: How To Create An IIFE Again?

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

Is IIFE relevant after ECMAScript2015?

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.

--

--

Karthick Ragavendran
Karthick Ragavendran

Written by Karthick Ragavendran

Fullstack engineer | React, Typescript, Redux, JavaScript, UI, Storybook, CSS, UX, Cypress, CI/CD.

No responses yet