Skip to content

Instantly share code, notes, and snippets.

@Aldizh Aldizh/counter.js
Last active Sep 20, 2019

Embed
What would you like to do?
Basic counter that demonstrates javascript closure concept
// In the function below changeBy is a private function
// whereas increment and decrement are public and hence
// can be invoked outside the Counter's scope
function Counter(initialCounter) {
var privateCounter = initialCounter || 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
};
var counter = new Counter(1);
console.log(counter.value()); // logs 1
counter.increment();
counter.increment();
console.log(counter.value()); // logs 3
counter.decrement();
console.log(counter.value()); // logs 2
// should give an error as it is out of scope
// console.log(counter.changeBy(1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.