A closure is a link between a function and its outer lexical (ie. as-written) environment, such that the identifiers (variables, parameters, function declarations etc) defined within the outer lexical environment are visible from within the function, regardless of when or from where the function is invoked.
A closure is a link between a function and its outer lexical (ie. as-written) environment, such that the identifiers (variables, parameters, function declarations etc) defined within the outer lexical environment are visible from within the function, regardless of when or from where the function is invoked.
In the terminology of the ECMAScript specification, a closure can be said to be implemented by the [[Environment]][[Environment]] reference (whichof every function-object, which points to the outer lexical environment) of within which the function is defined.
When a function is invoked via the internal [[Call]] method, the [[Environment]] reference on the function-object, which is then copied into the outer environment reference of the environment record of the newly-created execution context created when the function is invoked via the internal [[Call]] method(stack frame).
In the following example, function h closes over the lexical environment of function g (which, which, in turn, closes over the lexical environment of the global execution context.)
If an inner function is returned by an outer, then the outer lexical environment will persist after the outer function has returned. This is because the outer lexical environment needs to be available whenif the inner function is eventually invoked.