Technology Guides and Tutorials

Understanding JavaScript Closures

What is a JavaScript Closure?

A JavaScript 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, and it has access to the global variables.

How Do JavaScript Closures Work?

A closure is created when an inner function is defined inside an outer function. The inner function has access to the outer function’s variables, which are kept in the closure. The closure is created at the time the outer function is executed, and the inner function keeps a reference to the outer function’s variables. This means that the inner function can access the outer function’s variables even after the outer function has returned.

Example of JavaScript Closure

To understand how closures work, let’s look at an example. In the following code, the outer function is called “makeAdder” and the inner function is called “adder”. The outer function takes a parameter (x) and returns the inner function. The inner function takes a parameter (y) and returns the sum of x and y.

function makeAdder(x) {
return function(y) {
return x + y;
};}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2)); // 7
console.log(add10(2)); // 12

In this example, the makeAdder function is executed with the argument 5. This creates a closure that contains the variable x with the value 5. The function add5 is assigned the return value of makeAdder, which is the inner function adder. The function add10 is also assigned the return value of makeAdder, but with the argument 10. This creates a closure that contains the variable x with the value 10.

When the inner functions are called, they have access to the variables in their respective closures. When add5 is called with the argument 2, it adds the value of x (5) to the argument (2) and returns the result (7). Similarly, when add10 is called with the argument 2, it adds the value of x (10) to the argument (2) and returns the result (12).

Conclusion

JavaScript closures are an important concept to understand in order to write effective JavaScript code. Closures allow inner functions to access the variables of the outer function, even after the outer function has returned. This allows for the creation of functions that can maintain state, which can be useful for creating modules and other powerful JavaScript applications.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *