Creating an Immediately Invoked Function Expression in JavaScript

An Immediately Invoked Function Expression (IIFE) will execute immediately without needing to be called.

A common use for an IIFE is to prevent polluting the outer scope. Variables declared inside the IIFE are not accesable outside of that IIFE.

// this function will be immediately invoked
    var x = "inside an IIFE!";

// referencing x outside of the IIFE above will result in an error because x is not defined.

By wrapping the function in parenthesis, the parser knows to interpret it as a function expression and not a function declaration.

more JavaScript posts