Skip to content

Instantly share code, notes, and snippets.

@jpschroeder
Last active November 23, 2015 04:10
Show Gist options
  • Save jpschroeder/b2b71c3a3a9227e0f048 to your computer and use it in GitHub Desktop.
Save jpschroeder/b2b71c3a3a9227e0f048 to your computer and use it in GitHub Desktop.
Closures in Javascript
"use strict";
// A closure is a function that has one or more variables bound to it.
// In the following simple example, notice that the sayHi function accesses the greeting variable
// from outside of its scope. This is possible due to lexical scoping in javascript.
var greetingFactory = function() {
var greeting = 'Hello there'
var sayHi = function(name) {
return greeting + ' ' + name;
}
return sayHi;
}
// When greetingFactory returns, the greeting variable has gone out of scope.
// However, its value is bound to the sayHi function that is returned.
// The sayHi function remembers the environment in which it was created.
// The return value is then assigned to the hiGreeter function below.
// hiGreeter is now a closure.
// hiGreeter now references the sayHi function with the value of the greeting variable enclosed in it.
var hiGreeter = greetingFactory();
var out = hiGreeter('John')
console.log(out);
// This prints: Hello there John
// To make this example (ever so slightly) more interesting,
// I can pull the greeting value out as a parameter to greetingFactory.
// I can now make multiple different functions using the factory that use different greeting values
greetingFactory = function(greeting) {
var sayHi = function(name) {
return greeting + ' ' + name;
}
return sayHi;
}
var saluteGreeter = greetingFactory('Salutations');
var ahoyGreeter = greetingFactory('Ahoy hoy');
var salute = saluteGreeter('Alley');
console.log(salute);
// This prints : Salutations Alley
var ahoy = ahoyGreeter('Matthew');
console.log(ahoy);
// This prints: Ahoy hoy Matthew
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures for a much better explanation that this one
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment