Skip to content

Instantly share code, notes, and snippets.

@deanmarano
Created October 2, 2015 01:25
Show Gist options
  • Save deanmarano/740cc978d70ee463ec5e to your computer and use it in GitHub Desktop.
Save deanmarano/740cc978d70ee463ec5e to your computer and use it in GitHub Desktop.
Scopes vs. Closures

Scopes vs. Closures

Scopes and closures are often confused since they are so closely related. In your day to day life, it's somewhat rare that you'll need to know the difference. However, if you enjoy using the debugger, this may have bit you without you even knowing it.

Scope

https://developer.mozilla.org/en-US/docs/Glossary/Scope In Javascript, creating a new function creates a new scope. These are the variables that are defined in the current frame of the stack.

Closure

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures A closure includes all variables in your scope that were actually used in the function. i think about this as an array of pointers to variables in the other scope that were used.

An Example

In the Javascript above, what is in scope and what is not in scope is commented.

The interesting thing is walking through this and hitting the debugger. If, in the debugger console, you type console.log(b) you'll get a ReferenceError. Although b is in scope, it was not pulled into the function when it was called because it was never used. To get around this, you can put b; on it's own line, which will pull it into the closure so you can use it.

function outerFunction() {
var a = 1; // In scope of both otherFunction and innerFUncion, and in closure of innerFunction
var b = 2; // In scope of both outerFunction and innerFunction, but not in closure of innerFunction
function innerFunction() {
var c = 3; // In scope of innerFunction, not in scope of outerFunction
console.log(a);
debugger;
}
innerFunction();
}
outerFunction();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment