Thursday, September 24, 2015

Immediately-Invoked Function Expression : what and why?

I remember I was confused by the syntax of Immediately-Invoked Function Expression in my early days with JavaScript. I'll follow DRY principle in this blog post and shall point to the articles that I found most helpful when I learned this.

The definitive explanation with very good examples can be found in Ben Alman's blog post. He actually coined the term IIFE which was widely adopted later in JavaScript community.

Why and when to use IIFE? 2 cases are recurring:
1) create private namespace: We can create private functions and properties and can expose only those members intended to be public. This helps us not to pollute global namespace. Vivin Paliath explained this really well on stackoverflow.

2) resolve global variable conflict: Josh Mock gave a good example of this.

No comments:

Post a Comment