Skip to content

Instantly share code, notes, and snippets.

@67hz
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 67hz/08da59f1ede0bcf69c75 to your computer and use it in GitHub Desktop.
Save 67hz/08da59f1ede0bcf69c75 to your computer and use it in GitHub Desktop.
Closure demystified. Closure is best expressed when a function returns an anonymous function. If the nested anonymous function references a variable within the parent function context, that variable reference will be accessible when the nested function is invoked.
var multiplyByNumber = function (x) {
return function(y) {
// this nested anonymous function references
// parent 'x' arg variable
return x * y;
}
}
/**
* multiplyBy5 below is a function because multiplyByNumber returns a function.
* To reiterate, the below statement is the equivalent of
* var multiplyBy5 = function(y) {
* return 5 * y;
* }
*/
var multiplyBy5 = multiplyByNumber(5);
var multiply10x5 = multiplyBy5(10);
console.log(multiply10x5); // logs 50
/**
* So we see closure in action. multiplyBy5 points to the nested anonymous
* return function within multiplyByNumber and
* that nested function was initially given an 'x' value of 5 on line 16.
* This accessible 'x' value from the multipylyByNumber function context is available
* because of closure. When this child function is invoked it still
* has access to the parent's function scope.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment