public
Last active

best explanation of Javascript Closure, ever

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Here is a case that might surprise you:
 
var variable = "top-level";
function parentFunction() {
var variable = "local";
function childFunction() {
print(variable);
}
return childFunction;
}
 
var child = parentFunction();
child();
 
parentFunction returns its internal function, and the code at the bottom calls this function. Even though parentFunction has finished executing at this point, the local environment where variable has the value "local" still exists, and childFunction still uses it. This phenomenon is called closure.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.