LearnFrenzy
Sign in Take a free test

Variables: var, let and const · Variables Coding Problems · Question 2

A counter that keeps its own state in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links