JavaScript closure is a powerful feature that allows a function to access variables from an outer scope even after the outer function has returned. It is created when a function is defined within the scope of another function, and the inner function has access to the variables in the outer function's scope.
One way to create closure is by defining a function inside another function and returning the inner function. For example:
1function outer() {2 let outerVariable = 'I am the outer variable';3
4 function inner() {5 console.log(outerVariable);6 }7
8 return inner;9}10
11let closure = outer();12closure(); // logs "I am the outer variable"
In this example, the inner function has access to the outerVariable
even after the outer function has returned. This is because the inner function is returned as a closure, which retains a reference to the outerVariable
.
Closure can help create private variables and methods. For example:
1function counter() {2 let count = 0;3
4 return {5 increment: function () {6 count++;7 },8 getCount: function () {9 return count;10 },11 };12}13
14let counterA = counter();15counterA.increment();16console.log(counterA.getCount()); // logs 117
18let counterB = counter();19counterB.increment();20console.log(counterB.getCount()); // logs 1
In this example, the count variable is private to the counter function and can only be modified by the increment
and getCount
functions. This allows us to create multiple instances of a counter, each with its private count variable.
Closure can also be useful for creating function factories. For example:
1function createMultiplier(multiplier) {2 return function (num) {3 return num * multiplier;4 };5}6
7let triple = createMultiplier(3);8console.log(triple(5)); // logs 159
10let quadruple = createMultiplier(4);11console.log(quadruple(5)); // logs 20
In this example, the createMultiplier
function creates and returns a new function that multiplies its input by a specified multiplier. This allows us to easily create functions that perform a specific multiplication without defining a new function for each multiplier.
There are several benefits to using closure in JavaScript:
In summary, closure is a powerful feature of JavaScript that allows us to create private variables and methods and create function factories. It is essential to understand how closure works to use it in your code effectively.
Sign up to get updates when I write something new. No spam ever.
Subscribe to my Newsletter