Understanding Closures in Javascript

| Comments

Closure is when a function ‘remembers’ its lexical scope even when the function is executing outside that lexical scope. ~ Kyle Simpson

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: - It has access to its own scope (variables defined between its curly brackets) - It has access to the outer function’s variables - It has access to the global variables

The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var pizza = function() {
  var crust = "thin";
  var toppings = 3;
  var hasBacon = true;

  var getToppings = function() {
    return toppings;
  }

  var pizzaInfo = {};
  pizzaInfo.getToppings = getToppings;

  return pizzaInfo;
}

var pizzaA = new pizza();

pizzaA.getToppings(); // returns 3
  • Closures are useful in hiding the implementation of functionality while still revealing the interface
  • Closure is one way of supporting first-class functions; it is an expression that can reference variables within its scope (when it was first declared), be assigned to a variable, be passed as an argument to a function, or be returned as a function result.
References:

Comments