background-shape
feature-image

Closure is often confused with Lexical Scope. Lexical Scope is an important part of closure, but it is not closure by itself. Let’s understand what a Lexical Scope is first.

Lexical Scope

Lexical scoping defines how variable names are resolved in nested fuction. For example, if we have child function within a parent function, then the child funtion can access to variables in child function as well as the parent function.

1
2
3
4
5
6
function parent() {
  var x = 10;
  function child() {
    console.log(x); // Lexical scoping
  }
}

Closure

A Closure is a function that has access to the parent scope and preserves it, even after the parent function has closed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function parent() {
  var x = 10;
  function child() {
    x += 1;
    console.log(x);
  }
  return child;
}
var child = parent();
child(); // 11
child(); // 12
child(); // 13