Understanding Closures in JavaScript
A closure in JavaScript, is simply a function that remembers and has access to variables from it’s outer scope, even after that function has been popped off it’s execution context.
Get ATM Tahsin’s stories in your inbox
Join Medium for free to get updates from this writer.
Let us look at an example:
function bankBalance(){
let balance = 0;return function addMoney(){
balance++; // 1. Increment the balance first
console.log(balance); // 2. Log the new balance
return balance; // 3. Return the value
}
}const myClosure = bankBalance();
myClosure(); // Logs: 1
myClosure(); // Logs: 2
myClosure(); // Logs: 3
As you can see, we 1st make a bankBalance() function which returns another function addMoney(), due to closure myClosure() function has access to balance variable from its outer scope bankBalance() function even after the bankBalance() function has been popped off it’s execution context. This allows myClosure to access and update the balance variable.







