Skip to content

Instantly share code, notes, and snippets.

@sircharleswatson
Created November 25, 2014 04:30
Show Gist options
  • Save sircharleswatson/66aaf96b5086a09c5f72 to your computer and use it in GitHub Desktop.
Save sircharleswatson/66aaf96b5086a09c5f72 to your computer and use it in GitHub Desktop.
Explaining JS closures
// before anything is done to the multiplier function
// it looks like this:
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
var twice = multiplier(2);
// Once the multiplier function gets set,
// this is what the multiplier function looks like:
function multiplier(2) {
return function(number) {
return number * 2;
}
}
// When you assign the result of the multiplier function
// to a variable, it looks like this:
function twice(number) {
return number * 2; // 2 is frozen in place from the multiplier function
};
// Then when the twice function is called it looks like this:
twice(5) {
return 5 * 2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment