JavaScript has lexical scope— meaning code can only access variables defined in the same block. However, we can write code in a way that allows us to execute a function outside of its lexical scope.

The return keyword makes any defined variable or value available outside the function after the function is called.

We create a closure any time an outer function returns a reference to an inner function. And when we invoke that inner function (closure) from outside its original context, it still has access to its original lexical scope:

var newYorkCity = function() {
  var localString = "I exist in New York City!";

  var centralPark = function() {

  return centralPark;

var centralParkIsWhere = newYorkCity(); // closure!

centralParkIsWhere(); // prints "I exist in New York City!"

When would I use a closure?

Closures allow you to emulate private methods— where a public function can access private functions and variables. Using closures in this way is known as the module pattern.

Common Gotchas:

  • Creating closures in loops
    • Where our loop will complete iteration before any callbacks execute. Therefore, it’ll report the same context every time (the last iteration). This is known as close over.
    • Instead, consider using the let keyword introduced in ES2015 instead of var so that every closure binds the block-scoped variable.

Immediately Invoked Function Expressions (IIFE)

(Pronounced “iffy”)

Considering the following function declaration:

function sayHello() {

sayHello(); // prints "Hello!"

We declare a function called sayHello and then immediately invoke it. JavaScript provides another way of doing this using an IIFE, which allows us to declare & immediately invoke in one command:

(function sayHello() {
})(); // prints "Hello!"

When would I use an IIFE?

An IIFE is useful when trying to reduce the number of variables used in a scope. As programs grow in size, so do the number of variables required to perform operations. Too many variables can, in a sense, “clutter” the various scopes of a program.

In comparison to closures, IIFEs allow us to hide variables/functions from the global scope:

(function sayHello() {
})(); // prints "Hello!"

sayHello(); // ReferenceError: sayHello is not defined

Considering Performance

Closures help keep your code DRY, but use closures only when it is needed for a particular task. Creating these functions unnecessarily will negatively affect processing speed & memory consumption.

IIFEs can be used to hide functions from the global scope and allow you to declare and perfom unique operations in the moment. IIFEs are powerfully used as conditional anonymous functions within your software’s business logic.