Skip to content

Instantly share code, notes, and snippets.

@ldco2016
Created December 27, 2017 01:43
Show Gist options
  • Save ldco2016/97198e3109783c54ad0714f440e1855e to your computer and use it in GitHub Desktop.
Save ldco2016/97198e3109783c54ad0714f440e1855e to your computer and use it in GitHub Desktop.
This is an example of a closure for self-study
// 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