Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Created May 15, 2021 20:38
Show Gist options
  • Save helabenkhalfallah/07f7ea201f53197c10e304c1292159ab to your computer and use it in GitHub Desktop.
Save helabenkhalfallah/07f7ea201f53197c10e304c1292159ab to your computer and use it in GitHub Desktop.
JS Closure Example (1)
const counter = () => {
let privateCounter = 0;
const changeBy = (val) => {
privateCounter += val;
}
return ({
increment: () => {
changeBy(1);
},
decrement: () => {
changeBy(-1);
},
value: () => {
return privateCounter;
}
});
};
const counterFunc = counter();
console.log(counterFunc.value()); // 0
counterFunc.increment();
counterFunc.increment();
console.log(counterFunc.value()); // 2
counterFunc.decrement();
console.log(counterFunc.value()); // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment