Java Reference
In-Depth Information
degCent variable is left alone and still contains 10 . But what value does the return statement
return: the global or local degCent ?
The JavaScript engine begins the identifier lookup process in the current level of scope. Therefore,
it starts looking within the functional scope of convertToCentigrade() for a variable or function
with the name degCent , it finds the local variable, and uses its value in the return statement.
But if degCent was not created within convertToCentigrade() , the JavaScript engine would then
look in the next level of scope—the global scope in this case—for the degCent identifier. It would
find the global variable and use its value.
So now that you understand how scope works, revisit Example 1 in the “Fahrenheit to Centigrade
Function” Try It Out. Even though it has two degCent variables—one global and one local to
convertToCentigrade() —the code executes without a problem. Inside the function, the local
degCent variable takes precedence over the global. And outside of the function, the local variable is
no longer in scope; therefore, the global degCent is used.
Although it's perfectly valid to use the same identifier for global and local variables, it is highly
recommended that you avoid doing so. It adds extra, and often unnecessary, complexity and
confusion to your code. It can also make it easier to introduce bugs that are difficult to find and fix.
Imagine that, within a function, you modified a local variable when you meant to modify a global
variable. That is a bug, and if you replicated it in many other functions, you will spend precious
time finding and fixing those errors.
funCtions as Values
JavaScript is a powerful language, and a lot of that power comes from functions. Unlike many other
languages, functions are first‐class citizens in JavaScript; in other words, we can treat functions
just like any other type of value. For example, let's take the convertToCentigrade() function and
assign it to a variable:
function convertToCentigrade(degFahren) {
var degCent = 5/9 * (degFahren - 32);
return degCent;
}
var myFunction = convertToCentigrade;
This code assigns the convertToCentigrade() function to the myFunction variable, but look
closely at the right‐hand side of the assignment—the opening and closing parentheses are missing at
the end of the convertToCentigrade identifier. It looks a lot like a variable!
In this statement, we are not executing convertToCentigrade() ; we are referring to the actual
function itself. This means that we now have two ways of executing the same function. We can call
it normally by executing convertToCentigrade() , or we can execute myFunction() , like this:
var degCent = myFunction(75); // 23.88888889
var degCent2 = convertToCentigrade(75); // 23.88888889
 
Search WWH ::




Custom Search