A closure is a function that has access to its outer scope's variables, even when the outer function has finished execution. This allows the inner function to "remember" the variables and use them as needed.
A closure in JavaScript is a function that remembers the variables from its outer (enclosing) function’s scope, even after the outer function has executed.
# How Closures Work
A closure is created when:
1. A function is defined inside another function.
2. The inner function retains access to the variables of the outer function even after the outer function has finished executing.
Example:
function outer() {
let count = 0;
function inner() {
count++;
console.log(count);
}
return inner;
}
const counter = outer();
counter(); // 1
counter(); // 2
# How do you use closures to create private variables?
Closures can encapsulate variables, making them accessible only through
returned functions, thus creating private variables.
Closures help hide variables from the global scope, simulating private variables:
Example:
function bankAccount(initialBalance) {
let balance = initialBalance;
return {
deposit: function(amount) {
balance += amount;
},
getBalance: function() {
return balance;
}
};
}
const account = bankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
# How do closures help in data privacy?
Closures help by encapsulating data, making variables accessible only through
specific functions, thus preventing direct external modification
function createPerson(name) {
let age = 0;
return {
getName: () => name,
getAge: () => age,
setAge: (newAge) => age = newAge
};
}
const person = createPerson("Alice");
console.log(person.getName()); // Alice
person.setAge(30);
console.log(person.getAge()); // 30