Middle+
Implement a counter function with closure, where the counter cannot be changed from outside.
sobes.tech AI
Answer from AI
Here's an example of a counter function in JavaScript using closure, where the internal counter value is inaccessible from outside and can only be changed through methods:
function createCounter() {
let count = 0; // private variable
return {
increment() {
count++;
return count;
},
decrement() {
count--;
return count;
},
getValue() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getValue()); // 2
// Cannot directly change count, for example counter.count = 100 will not affect the internal value
Thus, the variable count is encapsulated and accessible only through the object's methods.