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.
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.
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.
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.