Immediately-invoked function expression(IIFE) | Codeexecute

Immediately-invoked function expression(IIFE)

Working with Javascript you might have been come accross the code like this:

(function () {

Yes, ofcourse being a JS developer you have seen this code and probably a lot of you know the term used to refer this type of construct. and you guessed it right!!

Immediately-Invoked Function Expression, or IIFE

According to Wikipedia

An immediately-invoked function expression (or IIFE, pronounced “iffy”)is a JavaScript programming language idiom which produces a lexical scope using JavaScript’s function scoping. Immediately-invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.

Too much to digest!! Isn’t it? So let’s make it simple by an example

Create a file index.html and paste the follwoing code into it

Here you can see that in console if you type foo You can access that, Since JS is not having any block scope so to avoid the global namespace, We can enclose the complete code in a function which may or may not have a name. Thus enclosed code within this type of function is termed as IIFE.

The first pair of parentheses (function(){...}) turns the code within (in this case, a function) into an expression, and the second pair of parentheses (function(){...})() calls the function that results from that evaluated expression.

Check the below code for reference

Here you can see that in console if you type foo you will get an error

Uncaught ReferenceError: foo is not defined
at :1:1

In this case we just saved our global variable to be encapsulated within function block.