Closures in JavaScript ๐


By Ronak Wanjari | Intern at Devsync
Closures are one of the most powerful and sometimes confusing features in JavaScript. But once you understand them, youโll unlock a lot of potential in your coding skills!
๐ What is a Closure?
A closure is simply a function that remembers the variables from its outer scope even after the outer function has finished executing.
In other words:
Functions can "close over" variables and keep access to them.
๐ง How Does It Work?
Whenever you create a function inside another function, the inner function has access to:
Its own variables.
Variables of the outer function.
Global variables.
Even if the outer function is done executing, the inner function still remembers the outer variables. That "memory" is what we call a closure.
๐ง Simple Example:
javascriptCopyEditfunction outer() {
let count = 0;
function inner() {
count++;
console.log(count);
}
return inner;
}
const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3
๐ Even though outer()
has already run, the inner()
function still has access to count
โ thanks to closure.
๐ Why Are Closures Useful?
Data Privacy / Encapsulation
You can hide variables from the outside world.Function Factories
You can create multiple customized functions.Callback Functions & Event Handlers
Closures are heavily used in asynchronous code.
๐ Real-Life Usage Example
javascriptCopyEditfunction createPasswordManager(password) {
return {
checkPassword: function(input) {
return input === password;
}
}
}
const manager = createPasswordManager("mySecret");
console.log(manager.checkPassword("wrong")); // false
console.log(manager.checkPassword("mySecret")); // true
Here, password
is completely private โ nobody can access it directly from outside the function. Closure helps us build this kind of private data protection.
๐ Quick Summary
Closure = Function + its Lexical Environment.
Functions remember the variables where they were created.
Powerful for data privacy, async programming, and interview questions!
๐ Iโm currently learning JavaScript as part of my internship at Devsync , and closures were one of the most mind-blowing topics I came across!
Subscribe to my newsletter
Read articles from ronak wanjari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
