Java Reference
In-Depth Information
When you load this page into your browser, you should see exactly the same results that you had with
ch3_examp4.htm.
At the top of the script block you declare your
convertToCentigrade()
function. You saw this func-
tion earlier:
function convertToCentigrade(degFahren)
{
var degCent;
degCent = 5/9 * (degFahren - 32);
return degCent;
}
If you're using a number of separate script blocks in a page, it's very important that the function be
defi ned before any script calls it. If you have a number of functions, you may want to put them all in
their own script block at the top of the page — between the <head> and </head> tags is good. That way
you know where to fi nd all your functions, and you can be sure that they have been declared before
they have been used.
You should be pretty familiar with how the code in the function works. You declare a variable
degCent
,
do your calculation, store its result in
degCent
, and then return
degCent
back to the calling code. The
function's parameter is
degFahren
, which provides the information the calculation needs.
Following the function declaration is the code that executes when the page loads. First you defi ne the
variables you need, and then you have the two loops that calculate and then output the results. This is
mostly the same as before, apart from the fi rst for loop.
for (loopCounter = 0; loopCounter <= 2; loopCounter++)
{
degCent[loopCounter] = convertToCentigrade(degFahren[loopCounter]);
}
The code inside the fi rst
for
loop puts the value returned by the function
convertToCentigrade()
into the
degCent
array.
There is a subtle point to the code in this example. Notice that you declare the variable degCent
within your function convertToCentigrade(), and you also declare it as an array after the function
defi nition.
Surely this isn't allowed?
Well, this leads neatly to the next topic of this chapter — variable scope.
Variable Scope and Lifetime
What is meant by
scope
? Well, put simply, it's the scope or extent of a variable's availability — which
parts of your code can access a variable and the data it contains. Any variables declared in a web page
outside of a function will be available to all script on the page, whether that script is inside a function or
otherwise — we term this a
global
or
page-level scope
. However, variables declared inside a function are