Skip to content

OutputNot attempted

Independent counters; destructured method

function makeCounter() {
let count = 0;
return { inc: () => ++count, get: () => count };
}
const a = makeCounter();
const b = makeCounter();
a.inc();
a.inc();
b.inc();
console.log(a.get(), b.get());
const { inc } = a;
inc();
console.log(a.get());

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

Each makeCounter call creates its own count. inc is an arrow that closes over count, it never used this, so destructuring it does NOT break it (contrast with this-binding drills).