Skip to content

Instantly share code, notes, and snippets.

@lorenzofelletti
Last active May 7, 2020 10:01
Show Gist options
  • Save lorenzofelletti/b85dee20afc4da3e5ddbc4db00809ad3 to your computer and use it in GitHub Desktop.
Save lorenzofelletti/b85dee20afc4da3e5ddbc4db00809ad3 to your computer and use it in GitHub Desktop.
JS Closures
function makeCounter(i) {
let count = i;
let toString = () => `The count is ${count}.`;
return {
add: () => ++count,
sub: () => --count,
val: () => count,
toString: toString
};
}
var counter = makeCounter(0);
console.log(counter.add()) // 1
console.log(counter.val()) // 1
console.log(counter.sub()) // 0
console.log(counter.add()) // 1
console.log(counter.add()) // 2
console.log(counter.toString()) // The count is 2.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment