JavaScript Closure


JavaScript variables can be local variables or global variables.

Private variables can use closures.


Global variable

Functions can access variables defined inside the function, such as:

Example

function myFunction() {
     var a = 4;
     return a * a;
}

Try It! 

Functions can also access variables defined outside the function, such as:

Example

var a = 4;
function myFunction() {
     return a * a;
}

Try It! 

In a later example, A is a global variable.

Global variables in web pages belong to the window object.

Global variables can be applied to all scripts on the page.

In a first example, A is a local variable.

Local variables can only be used to define other functions. It is not available for other functions or script codes.

Even if the names of global and local variables are the same, they are two different variables. Modifying one of them will not affect the value of the other.

Note If the var keyword is not used when a variable is declared , then it is a global variable, even if it is defined within a function.

Variable life cycle

The scope of global variables is global, that is, global variables are everywhere in the entire JavaScript program.

The variables declared inside the function only work inside the function. These variables are local variables, and the scope is local; the parameters of the function are also local and only work inside the function.


Counter dilemma

Imagine if you want to count some values, and the counter is available in all functions.

You can use global variables and functions to set the counter to increment:

Example

var counter = 0;

 

function add() {

    return counter += 1;

}

 

add();

add();

add();

 

// now, counter is 3

 Try It! 

JS console log

The counter value changes when the add() function is executed.

But here comes the problem. Any script on the page can change the counter, even if the add() function is not called.

If it declare the counter in the function, the value of the counter cannot be modified without calling the function:

Example

function add() {
     var counter = 0;
     return counter += 1;
}
 
add();
add();
add();
 
// The original intention was to output 3, but it was counterproductive, and the output was all 1!

Try It! 

console log

The above code will not be output correctly. Every time I call the add() function, the counter will be set to 1.

JavaScript built-in functions can solve this problem.


JavaScript built-in functions

All functions can access global variables.  

In fact, in JavaScript, all functions can access their upper level scope.

JavaScript supports nested functions. Nested functions can access the function variables of the previous level.

In this example, the built-in function plus() can access the counter variable of the parent function :

Example

function add() {
     var counter = 0;
     function plus() {counter += 1;}
     plus();
     return counter;
}

Try It! 

If we can access the plus() function externally , then we can solve the dilemma of the counter.

We also need to ensure that counter = 0 is executed only once.

We need closures.


JavaScript closure

Remember the function calls itself? What will this function do?

Example

var add = (function () {
     var counter = 0;
     return function () {return counter += 1;}
})();
 
add();
add();
add();
 
// The counter is 3

Try It! 

Example analysis

The variable add specifies the return word value of the function self-call.

The self-calling function is executed only once. Set the counter to 0. And return the function expression.

The add variable can be used as a function. The great part is that it can access counters in the upper scope of the function.

This is called a JavaScript closure. It makes it possible for functions to have private variables.

The counter is protected by the scope of the anonymous function and can only be modified by the add method.

Note

Closure is a mechanism to protect private variables, forming a private scope when the function is executed, and protecting the private variables inside from outside interference.

Intuitively, it forms a stack environment that is not destroyed.