Curly Jail

Psssst! Have you ever been unsuccessful in successfully ignoring what following JavaScript construct does?

(function () {


Well, I have been there. Trust me!

Good thing is that I have learned it well and in around 3 minutes you will also be able to brag blog about it.

That construct is called Immediately Invoked Function Expression (IIFE).

IIFE means, a function which gets executed immediately. Think of it as a function getting called automatically, when an interpreter reaches that function.

Most Common Use Case:

One of the most common use case of IIFE is to limit scope of a variable made via var. Variables created via var have a scope limited to a function, so this construct (which is essentially a function wrapper around certain code) will make sure that your variable’s scope does not leak out of that function.

In following example, count will not be available outside the immediately invoked function i.e. scope of count will not leak out of the function. You will get a Reference Error, should you try to access it outside of the immediately invoked function.

(function () {
var count = 10;
console.log(count); // Reference Error: count is not defined

ES6 Alternative (Recommended):

In ES6, we now can have variables created via let and const. Both of them are block-scoped (unlike var which is function-scoped).

Therefore, instead of using that complex construct of IIFE for the use case mentioned above, you can now write following much much simpler code to make sure that a variable’s scope does not leak out of your desired block of code.



    let count = 10;


console.log(count); // Reference Error: count is not defined


In this example we used let to define count variable which makes count limited to the block of code, we created via curly brackets {…}.

I call it a Curly Jail.

P.S. Here is this answer on StackOverFlow. Feel free to Upvote it. I don’t mind, I swear. 😀





Subscribe: rss | email