Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
WORKING WITH SCOPE AND CLOSURES
When discussing scope it’s important to consider where a variable is defined as well as its lifetime. Where is the variable accessible? In the case of JavaScript, scope is maintained at the function level, not the block level. Hence, variables defined with the keyword var and parameters are visible only inside the function in question.
A nested function has access to its outer function’s variables, except for this and arguments. The mechanism through which a nested function continues to keep the references of its outer function even after the outer function finishes execution is called closure. Closures also help to reduce namespace pollution.
Each time an enclosed function is called, a new scope is created, although the code doesn’t change. The following code shows this behavior.