HTML and CSS Reference
In-Depth Information
EXAMPLE 7.6
<html>
<head><title>Return Value</title>
<script type="text/javascript">
1
function mileage(miles, gas){
2
return miles/gas;
// Return the result of the division
}
</script>
</head>
<body bgcolor="lightgreen">
<font face="arial" size="+1">
<div align="center">
<img src="car-wave.gif">
<script type="text/javascript">
3
var distance=eval(prompt("How many miles did you
drive? ", ""));
var amount=eval(prompt("How much gas did you use?", ""));
4
var rate = mileage(distance, amount);
// Return value assigned to rate
5
alert("Your mileage "+ rate +" miles per gallon.\n");
</script>
</div>
</font>
</body>
</html>
EXPLANATION
1
A function called mileage() is defined in this JavaScript program located between
the <head> tags of the document.
2
The return statement sends back to the caller of the function the result of the di-
vision. That returned value will be assigned to the variable, rate , on line 4.
3
The user is asked for input. The number of miles driven and the amount of gas
used are assigned to the variables called distance and amount , respectively (see
Figure 7.9).
4
The mileage() function is called, passing two arguments. Because the mileage()
function is on the right side of the assignment operator (the = sign), whatever is
returned from the function will be assigned to the variable, called rate , on the left
side of the = sign.
5
The alert dialog box displays the value returned from the function: the number of
miles used per gallon (see Figure 7.10).
Search WWH ::




Custom Search