English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript Basic Tutorial

JavaScript Object

JavaScript Function

JS HTML DOM

JS Browser BOM

AJAX Basic Tutorial

JavaScript Reference Manual

JavaScript Closure

JavaScript variables can belong toLocalScope orGlobalScope.

Can be usedClosureSet global variables as local (private).

Why do we need closures?

Suppose we want to use a variable to count something and want the counter to be available to all functions.

We can use a global variable and a function to increase the counter:

// Initialize counter
var counter = 0;
// Increment counter function
function increment() {
  counter++;
}
// Call increment() 3times
increment();
increment();
increment();
// Now the counter should be3
document.getElementById("output").innerHTML = `Counter: ${counter};`;
Test to see‹/›

The existing solution has a problem: Any code on the page can change the counter without calling increment().

JavaScript inner functions can solve this problem.

JavaScript Nested Functions

JavaScript supports nested functions. Nested functions can access the scope above them.

In this example, the inner function can access the counter variable from the outer function:

function outer() {
  var counter = 0;
  function inner() {
      counter++;
  }
  return counter; 
}
Test to see‹/›

Nested functions can solve the problem mentioned earlier, if we can access the inner() function from the outside.

We still need to find a way to execute counter = 0 only once, which is what we will discuss next: closures.

JavaScript Closure

A closure is a combination of a function and the lexical environment in which it was declared.

Closures can access variables from another function's scope. This is achieved by creating a function inside a function. Of course, the outer function cannot access the inner scope.

var increment = (function() {
  var counter = 0;
  function inner() {
      return ++counter;
  }
  return inner;
})();
Test to see‹/›

The return value of the self-executing function is assigned to the variable increment.

The self-executing function runs only once. It sets the counter to zero and returns the function expression.

A closure is a function that can access the parent scope even after the parent function has closed.