Skip to content

Instantly share code, notes, and snippets.

@joepie91
Last active October 14, 2018 05:54
Show Gist options
  • Save joepie91/cb0e42c3562bc94e4491 to your computer and use it in GitHub Desktop.
Save joepie91/cb0e42c3562bc94e4491 to your computer and use it in GitHub Desktop.
Javascript Closures illustrated
functionCreator = function(favouriteNumber) {
return function(inputNumber) { // <-- This function is a closure!
console.log("You input the number " + inputNumber + ", and your favourite number is " + favouriteNumber + ".");
if(inputNumber === favouriteNumber) {
console.log("Those are the same number!");
} else {
console.log("Those are NOT the same number!");
}
}
}
numberFunc = functionCreator(7);
numberFunc(7); // You input the number 7, and your favourite number is 7. Those are the same number!
numberFunc(13); // You input the number 13, and your favourite number is 7. Those are NOT the same number!
// Now let's do it a little briefer... Note how we just directly call the return value, rather than assigning it to `numberFunc` first.
functionCreator(7)(13); // You input the number 13, and your favourite number is 7. Those are NOT the same number!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment