Skip to content

Instantly share code, notes, and snippets.

@iwek
Last active January 14, 2016 16:42
Show Gist options
  • Save iwek/4576677 to your computer and use it in GitHub Desktop.
Save iwek/4576677 to your computer and use it in GitHub Desktop.
JavaScript Closure Example
function f(y) {
var z = 1;
return function g(y) {
alert(y + z);
}
}
var z=10;
f(); //returns the function: function g(y) {alert(y + z);}
f()(2); //grabs function g, assings 2 to y, knows z is 1 through closure scope and makes an alert(3)
//ANOTHER EXAMPLE
function f(y) {
var z = 1;
function g(y) {
alert(y + z);
}
g(y);
}
var z=10;
f(2); // calls f and alerts 3, inside g JavaScript knows variabe z because it is inside a Closure Scope.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment