JavaScript Design Pattern - IIFE

What is an IIFE?

IIFE (pronounced "iffy") stands for Immediately Invoked Function Expression.  The term was coined by Ben Alman back in 2010.  

An IIFE is a function that executes immediately after it is created.    

This is a popular design pattern in JavaScript and is widely considered to be a best practice. 


  'use strict';
  var msg = 'Hello world';

An anonymous function is wrapped in parentheses so the Javascript interpreter will treat it as a function expression and not a function declaration. 

What is the benefit?

Creating a closure allows the code to have local ("private") scope which prevents conflicts with other code and pollution of the global scope.