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
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.
Take Away: How To Create An IIFE Again?
- Put the logic inside a function.
- Wrap the function with a grouping operator.
- 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.