Skip to content

Instantly share code, notes, and snippets.

@remyoudemans
Last active October 10, 2022 17:53
Show Gist options
  • Save remyoudemans/c66cc14d5d5271c4a6e5cf0f35b76b67 to your computer and use it in GitHub Desktop.
Save remyoudemans/c66cc14d5d5271c4a6e5cf0f35b76b67 to your computer and use it in GitHub Desktop.
Closures for private state
const makeCounter = () => {
let count = 0;
return {
get() {
return count;
},
increment() {
count += 1;
},
decrement() {
count -= 1;
}
}
}
const counter1 = makeCounter();
counter1.get(); // 0
counter1.increment();
counter1.get(); // 1
const counter2 = makeCounter();
counter2.get(); // 0
counter2.decrement(); // -1
// note that counter1 hasn't changed. They have separate values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment