Last active
October 14, 2018 05:54
-
-
Save joepie91/cb0e42c3562bc94e4491 to your computer and use it in GitHub Desktop.
Javascript Closures illustrated
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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