Created
December 27, 2017 01:43
-
-
Save ldco2016/97198e3109783c54ad0714f440e1855e to your computer and use it in GitHub Desktop.
This is an example of a closure for self-study
This file contains hidden or 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
// Closures will blow your mind or make you pull your hair out! | |
// One of the most difficult topics is that of closures. | |
// So I will write a small function that returns a function | |
// that calculates how many years we have left to retirement. | |
// retirementAge passes the age someone has to have | |
// in order to retire | |
function retirement(retirementAge) { | |
var a = ' years left until retirement.'; | |
// although execution function finished | |
// still able to use this variable even though | |
// execution stopped | |
return function(yearOfBirth) { | |
var age = 2017 - yearOfBirth; | |
console.log((retirementAge - age) + a); | |
} | |
} | |
// log to console | |
// storing the above function in this variable | |
// which then declares the a variable | |
// then the execution context finishes | |
var retirementUS = retirement(67); | |
retirementUS(1990); | |
// alternate way to log this | |
retirement(67)(1990); | |
// CLOSURES SUMMARY | |
// An inner function always has access to the variables and parameters of its outer | |
// function, even after the outer function has returned. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment