Immediately-invoked function expression

From Wiki @ Karl Jones dot com
Jump to: navigation, search

An immediately-invoked function expression (or IIFE, pronounced "iffy") is a JavaScript design pattern which produces a lexical scope using JavaScript's function scoping.

Description

Immediately-invoked function expressions can be used to:

  • Avoid variable hoisting from within blocks
  • Protect against polluting the global environment
  • Simultaneously allow public access to methods while retaining privacy for variables defined within the function

This pattern has been referred to as a self-executing anonymous function; Ben Alman introduced "IIFE" as a more semantically accurate term for the pattern, shortly after its discussion arose on comp.lang.javascript.

Code sample

(function(app) {
})(window.app || (window.app = {}));

See also

External links