Skip to content

Instantly share code, notes, and snippets.

@JoeKarlsson
Created September 8, 2016 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoeKarlsson/b9811dbe8997076db8b2b625fc50c361 to your computer and use it in GitHub Desktop.
Save JoeKarlsson/b9811dbe8997076db8b2b625fc50c361 to your computer and use it in GitHub Desktop.
Live Coding Closure Examples
var money = 55.50;
var coffeeCost = 8.50;
var drinkCoffee = (function(){
var cupsDrunk = 0;
return function(){
if( money >= coffeeCost ){
money -= coffeeCost;
cupsDrunk++;
}
return cupsDrunk; // return the value
};
})();
var count;
count = drinkCoffee(); // 1
count = drinkCoffee(); // 2
count = drinkCoffee(); // 3
console.log( count ); // 3
console.log( money ); // 30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment