Javascript: IIFE
In this blog, I will try to share my knowledge about the IIFE which stands for Immediately Invoked Function Expression.
As you already know, Global variables are bad because they can cause a lot of problems, and in modern javascript, we avoid this global variable problem by IIFE.
It is a function expression that looks like this,
And don't be confused because you already know this, what javascript engine will do with this code.
IIFE is a common javascript design pattern used by a lot of popular libraries like jquery etc. and the idea behind using this pattern is to place all the library code inside the local scope to avoid any namespace collision.
The first thing you should know is, by declaring ( ) we are saying to the javascript engine, this is not a function declaration, it's a function expression and after that, we created an anonymous function with no name, and then we immediately invoked this function.
Now you must be thinking what's the benefit of doing this?
So the main benefit of IIFE is we can define global properties inside the anonymous function and that will be scoped inside that IIFE only.
Example
While executing this code, the javascript engine will create a new execution context that has a new Variable Environment scope and this allows us to attach private data right in Variable Environment that can be accessed by Global execution Context.
As you can see from examples, it takes advantage of scopes, they enable us to attach private data to a function and create a fresh environment for us so we don't pollute our Global Execution Context. As we add more and more javascript files we want to make sure that we can wrap things in a function to scope things into their own environments and minimize the amount of data we place in the Global Execution Context.