HTML and CSS Reference
In-Depth Information
the programmer chooses the name. Heres an example of a function definition that returns the product of
the two arguments. As the name indicates, you could use it to compute the area of a rectangle.
function areaOfRectangle(wd,ln) {
return wd * ln;
}
Notice the return keyword. This tells JavaScript to send the result of the function back to us. In our
example, this lets us write something like rect1 = areaOfRectangle(5,10) , which would assign a value
of 50 (5 10) to our rect1 variable. The function definition would be written as code within the script
element. It might or might not make sense to define this function in real life because it is pretty easy to
write multiplication in the code, but it does serve as a useful example of a programmer-defined function.
Once this definition is executed, which probably would be when the HTML file is loaded, other code can
use the function just by calling its name, as in areaOfRectangle(100,200) or areaOfRectangle(x2-
x1,y2-y1) .
The second expression assumes that x1 , x2 , y1 , y2 refer to coordinate values that are defined elsewhere.
Functions also can be called by setting certain tag attributes. For example, the body tag can include a
setting for the onLoad attribute:
<body onLoad="init();">
My JavaScript code contains the definition of a function I call init . Putting this into the body element
means that JavaScript will invoke my init function when the browser first loads the HTML document or
whenever the player clicks on the reload/refresh button. Similarly, making use of one of the new features
of HTML5, I could include the button element:
<button onClick="throwdice();">Throw dice </button>
This creates a button holding the text Throw dice . When the player clicks it, JavaScript invokes the
throwdice function I defined in the script element.
The form element, to be described later, could invoke a function in a similar way.
Conditional statements: if and switch
The craps game has a set of rules. One way to summarize the rules is to say, if it is a first-throw situation,
we check for certain values of the dice throw. If its not the first throw, we check for other values of the
dice throw. JavaScript provides the if and switch statements for such purposes.
The if statement is based on conditions, which can be a comparison or a check for equality—for
example, is a variable named temp greater than 85 or does the variable named course hold the value
"Programming Games". Comparisons produce two possible logical values—true or false. So far youve
seen values that are numbers and values that are strings of characters. Logical values are yet another
data type. They are also called Boolean values, after the mathematician, George Boole. The condition and
check that I mentioned would be written in code as
temp>85
and
course == "Programming Games"
Read the first expression as: Is the current value of the variable temp greater than 85?
 
Search WWH ::




Custom Search