Write createCounter(start) that returns an object with increment, decrement and value methods. Two counters must not share their count.
Solution
main.js
function createCounter(start = 0) {
let count = start; // private: only the returned functions can reach it
return {
increment: () => ++count,
decrement: () => --count,
value: () => count,
};
}
const a = createCounter();
const b = createCounter(10);
a.increment();
a.increment();
b.decrement();
console.log("a:", a.value());
console.log("b:", b.value());
console.log("count visible outside?", typeof count);
Output Verified by running it on Node.js
a: 2
b: 9
count visible outside? undefined
Each call to createCounter creates a new count variable, and the three arrow functions close over it. Nothing outside can read or change it directly – data privacy through closures.
More Variables: var, let and const practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!