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