Skip to content

Instantly share code, notes, and snippets.

@joepie91 joepie91/closures.js

Last active Oct 14, 2018
Embed
What would you like to do?
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
You can’t perform that action at this time.