Java Reference
In-Depth Information
functional scope
Variables and functions declared inside a function are visible only inside that function—no code
outside the function can access them. For example, consider our standard convertToCentigrade()
function:
function convertToCentigrade(degFahren) {
var degCent = 5/9 * (degFahren - 32);
return degCent;
}
The degCent variable is defined inside the convertToCentigrade() function. Therefore, it can only
be accessed from within convertToCentigrade() . This is commonly referred to as functional or
local scope , and degCent is commonly called a local variable .
Function parameters are similar to variables; they have local scope, and thus can only be accessed
from within the function. So in the case of the previous convertToCentigrade() function,
degFahren and degCent are local variables.
So what happens when the code inside a function ends and execution returns to the point at which
the code was called? Do the variables defined within the function retain their value when you call
the function the next time?
The answer is no: Variables not only have the scope property—where they are visible—but they also
have a lifetime . When the function finishes executing, the variables in that function die and their
values are lost, unless you return one of them to the calling code. Every so often JavaScript performs
garbage collection (which we talked about in Chapter 2), whereby it scans through the code and sees
if any variables are no longer in use; if so, the data they hold are freed from memory to make way
for the data of other variables.
identifier lookup
What happens if you use the same variable name for both a global and local variable? JavaScript
handles this seemingly catastrophic event with a process called identifier lookup . An identifier
is simply the name you give a variable or function. So, identifier lookup is the process that the
JavaScript engine uses to find a variable or function with a given name. Consider the following
code:
var degCent = 10;
function convertToCentigrade(degFahren) {
var degCent = 5/9 * (degFahren - 32);
return degCent;
}
This code contains two degCent variables: One is global, and the other is local to
convertToCentigrade() . When you execute the function, the JavaScript engine creates the local
degCent variable and assigns it the result of the Fahrenheit‐to‐centigrade conversion—the global
 
Search WWH ::




Custom Search