Table of contents
No headings in the article.
Closures are an important concept in JavaScript that allow a function to access and use variables that are defined outside of its own scope. In other words, a closure is a function that has access to its own private scope, as well as to the outer scope in which it was created. Here are some important things to know about closures:
A closure is created whenever a function is defined inside another function.
A closure allows a function to access variables from the outer function even after the outer function has returned.
A closure forms a "bridge" between the inner function and the outer function, allowing them to share variables and maintain state.
Here's an example of a closure in JavaScript:
scssCopy codefunction outer() {
let count = 0;
function inner() {
count++;
console.log(count);
}
return inner;
}
let closure = outer();
closure(); // Output: 1
closure(); // Output: 2
closure(); // Output: 3
In this example, the outer
function defines a variable count
and a nested function inner
. The inner
function increments the count
variable and logs its value to the console. The outer
function returns the inner
function. When the outer
function is called and its return value is assigned to closure
, a closure is created. The closure
variable now holds a reference to the inner
function along with a private copy of the count
variable. Each time the closure
function is called, it accesses and updates the count
variable from its outer scope, resulting in the output 1
, 2
, and 3
in the console.
Here's a mini-project that demonstrates the use of closures in JavaScript:
scssCopy codefunction calculator() {
let total = 0;
function add(num) {
total += num;
return add;
}
function subtract(num) {
total -= num;
return subtract;
}
function multiply(num) {
total *= num;
return multiply;
}
function divide(num) {
total /= num;
return divide;
}
function getResult() {
return total;
}
return {
add,
subtract,
multiply,
divide,
getResult
};
}
let calc = calculator();
calc.add(5)(10)(15); // Output: undefined (chaining method calls)
calc.subtract(3)(1)(2); // Output: undefined (chaining method calls)
calc.multiply(2)(2); // Output: undefined (chaining method calls)
calc.divide(4)(); // Output: 5 (calling getResult to get the final result)
In this example, the calculator
function returns an object with four methods: add
, subtract
, multiply
, and divide
, along with a getResult
method that returns the current total. Each method returns itself to allow for method chaining. The calc
variable holds an instance of the calculator
object, which can be used to perform various mathematical operations. In this case, we chain method calls to add, subtract, multiply, and divide numbers, and then call the getResult
method to get the final result, which is 5
. This example demonstrates the power of closures in maintaining state and sharing variables between functions.