HTML and CSS Reference
In-Depth Information
Each time this function is executed it declares a new variable, which is scoped to the func-
tion. The keyword var is used to indicate that the variable is function scoped rather than
global scoped. The newly created variable has 1 added to it, and the value is returned. When
the function ends the variable is destroyed.
If we try to access the variable i outside the function an error will be generated:
> i
ReferenceError: i is not defined
The error is not because the variable is being accessed outside the function; it is because it
does not exist anymore. Function variables are placed on a stack when the function begins
execution, and when the function completes they are popped off the stack and destroyed.
Programming languages use this approach for good reason. This ensures the space alloc-
ated to variables inside functions is automatically reclaimed when the function completes.
This ensures against out of memory errors.
On the face of it this all seems to make sense. There are however good reasons why we may
wish to access function scoped variables even after functions complete. We do not however
want to make these variables global variables (as we could do by omitting the var keyword
on the variable declaration). This can be achieved via closures.
Consider the following code:
> function f2() {
var i = 0;
return function() {
return ++i;
This function does the following:
1. Declares a function scoped variable called i initialised to the value 0.
2. Returns a function that will increment this variable when invoked.
We can therefore call this function and assign the result (which is a function) to a variable:
> incrementer = f2()
Based on our explanation of the function scoped variables above, you would expect that the
variable declared inside f2 would be destroyed when the function call f2 completed. There-
Search WWH ::

Custom Search