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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response