JS Shorts — Immediately Invoked Function Expression (IIFE)

Prakhar Jaiswal
2 min readDec 1, 2020

Immediately Invoked Function Expression (IIFE) is a function expression that runs as soon as it’s defined.

An IIFE has the below syntax,

Generally, IIFEs can be used to guard against unintended effects of Hoisting.

Here, getValue gets it’s value from an IIFE which is called with an argument v = 1. As a result, even if we are changing the value later on, the value returned by the function remains as is.

IIFEs can also be used to enforce private variables and methods.

Here, the counter variable holds only the get and set functions as only these are returned by the IIFE. These get and set have the access to the variable i due to the scope in which they were defined. As a result, we have maintained the private variables while providing the full functionality using IIFEs.

Image by Pexels from Pixabay

— That’s all for today

--

--