Easy Tutorial
❮ Jsref Obj Array Jsref Class Super ❯

JavaScript Closure


JavaScript variables can be local or global.

Private variables can be utilized with closures.


Global Variables

A function can access variables defined inside the function, like this:

Example

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

A function can also access variables defined outside the function, like this:

Example

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

In the latter example, a is a global variable.

In a web page, global variables belong to the window object.

Global variables can be used by all scripts on the page.

In the first example, a is a local variable.

Local variables can only be used within the function they are defined. They are not available to other functions or script code.

Global and local variables with the same name are different variables. Modifying one does not affect the other.

| | If a variable is declared without the var keyword, it becomes a global variable, even if it is defined inside a function. | | --- | --- |


Variable Lifecycle

The scope of a global variable is global; it exists throughout the entire JavaScript program.

Variables declared within a function are local and only function within that function. These are local variables; their scope is local. Function parameters are also local and only function within the function.


Counter Dilemma

Imagine you want to count some values, and the counter should be available across all functions.

You can use a global variable and increment the counter with a function:

Example

var counter = 0;

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

add();
add();
add();

// The counter is now 3

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

However, any script on the page can change the counter, even without calling the add() function.

If I declare the counter inside a function, it cannot be modified without calling the function:

Example

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

add();
add();
add();

// Intended to output 3, but it outputs 1 each time!

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

JavaScript nested functions can solve this problem.


JavaScript Nested Functions

All functions can access global variables.

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

JavaScript supports nested functions. Nested functions can access variables from the parent function.

In this example, the nested function plus() can access the parent function's counter variable:

Example

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

If we could access the plus() function externally, this would solve the counter dilemma.

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

We need a closure.


JavaScript Closure

Remember the self-invoking function? What does this function do?

Example

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

add();
add();
add();

// The counter is 3

Example Explanation

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

The self-invoking function only executes once. It sets the counter to 0 and returns a function expression.

The add variable can be used as a function. The great part is that it can access the counter in the parent scope.

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

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

| | A closure is a mechanism to protect private variables. It forms a private scope during function execution, protecting private variables from external interference. It essentially creates a non-destroyed stack environment. | | --- | --- |

❮ Jsref Obj Array Jsref Class Super ❯