Closures in Javascript and its applications
Closures are a fundamental concept in JavaScript, and they are used extensively in modern programming. Simply put, a closure is a function that has access to variables in its outer function scope, even after the outer function has returned. In this way, closures allow for data encapsulation and private variables in JavaScript.
One common use case for closures is to create private variables and methods within an object. For example, suppose you wanted to create an object that has a public method for incrementing a counter, but you don’t want the counter variable to be accessible from outside the object. Here’s an example of how you could use a closure to achieve this:
function counter() {
let count = 0;
return {
increment: function() {
count++;
console.log(count);
}
};
}
const myCounter = counter();
myCounter.increment(); // logs 1
myCounter.increment(); // logs 2
In this example, the counter
function creates a private variable count
and returns an object with a public method increment
. The increment
method has access to the count
variable due to the closure created by the counter
function. When we call counter()
, we get back an object with a single method, increment
. We can then call myCounter.increment()
to increment the count and log the current value.
Another common use case for closures is to create functions that generate other functions with specific behavior. For example, suppose you wanted to create a function that generates functions that always add a specific value to a given argument. Here’s an example:
function adder(x) {
return function(y) {
return x + y;
};
}
const add5 = adder(5);
console.log(add5(3)); // logs 8
console.log(add5(7)); // logs 12
In this example, the adder
function takes a single argument x
and returns a new function that takes another argument y
and returns the sum of x
and y
. We can then create new functions with specific values of x
by calling adder
with the desired value. In this case, we create a new function add5
that adds 5 to its argument. We can then call add5(3)
and add5(7)
to get the sums 8 and 12, respectively.
Closures can also be used to create asynchronous behavior in JavaScript. For example, suppose you wanted to create a function that runs a callback after a certain delay. You could use a closure to store the timer ID and cancel the timer if necessary. Here’s an example:
function delay(callback, time) {
let timerId = setTimeout(function() {
callback();
}, time);
return function() {
clearTimeout(timerId);
};
}
const cancelDelay = delay(function() {
console.log('Delayed message!');
}, 1000);
// Cancel the delay before it executes
cancelDelay();
In this example, the delay
function takes two arguments: a callback function and a delay time in milliseconds. The function creates a new timer using the setTimeout
function and stores the timer ID in a variable. It then returns a new function that cancels the timer by calling clearTimeout
with the timer ID. We can then call the delay
function to schedule a callback after a certain delay and use the returned function to cancel the delay if necessary.
In conclusion, closures are a powerful and versatile feature of JavaScript that allows for data encapsulation, private variables, and complex behavior. By creating functions that have access to their outer scope, closures enable developers to create elegant and efficient.
Thanks for reading!
I hope you found this article useful. If you have any questions or suggestions, please leave comments. Your feedback helps me to become better.
Don’t forget to subscribe⭐️
Facebook Page: https://www.facebook.com/designTechWorld1
Instagram Page: https://www.instagram.com/techd.esign/
Youtube Channel: https://www.youtube.com/@tech..Design/
Twitter: https://twitter.com/sumit_singh2311
Gear used:
Laptop: https://amzn.to/3yKkzaC
Watch: https://amzn.to/41cialm
You can prefer React Book: https://amzn.to/3Tw29nx
Some extra books related to programing language:
*Important Disclaimer — “Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”