Q7 [Coding]: Implement a counter function using closures that supports increment, decrement, and getValue.
function createCounter(initialValue = 0) {
let count = initialValue;
return {
increment: () => ++count,
decrement: () => --count,
getValue: () => count
};
}
This encapsulates count inside a private closure, exposing only controlled modifier functions.
Key Takeaways
- Enables private variables without native class private fields.
- Exposes object methods that maintain access to closed-over state.
Knowledge Check
Can code outside createCounter access or modify the internal count variable directly?