Junior — Middle
How can closures be used to achieve data encapsulation in JavaScript?
sobes.tech AI
Answer from AI
In JavaScript, closures allow creating private variables that can only be accessed through specific functions, ensuring data encapsulation.
Example:
function createCounter() {
let count = 0; // private variable
return {
increment() {
count++;
return count;
},
getCount() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.getCount()); // 1
console.log(counter.count); // undefined — direct access is not possible
Here, count is not directly accessible from external code but can be accessed through the increment and getCount methods. This allows controlling access and modification of data, implementing encapsulation using closures.