1
Chapter 10 - JavaScript: Functions
Outline
10.1
10.2
10.3
10.4
10.5
10.6
10.7
10.8
10.9
10.10
10.11
10.12
10.13
Introduction
Program Modules in JavaScript
Programmer-Defined Functions
Function Definitions
Random-Number Generation
Example: Game of Chance
Duration of Identifiers
Scope Rules
JavaScript Global Functions
Recursion
Example Using Recursion: Fibonacci Series
Recursion vs. Iteration
JavaScript Internet and World Wide Web Resources
2001 Prentice Hall, Inc. All rights reserved.
2
10.2 Program Modules in JavaScript
main
worker1
worker4
worker2
worker3
worker5
Fig. 10.1 Hierarchical boss-function/worker-function relationship.
2001 Prentice Hall, Inc. All rights reserved.
3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Outline
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
SquareInt.html
<!-- Fig. 10.2: SquareInt.html -->
<!-- Square function
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>A Programmer-Defined square Function</title>
<script type = "text/javascript">
<!-Calling function square and
document.writeln(
"<h1>Square the numbers from 1 to 10</h1>" );
passing it the value of x.
// square the numbers from 1 to 10
for ( var x = 1; x <= 10; ++x )
document.writeln( "The square of " + x + " is " +
square( x ) + "<br />" );
// The following square Variable
function's
body
executed
y gets
theis
value
of variable
// only when the function is explicitly called.
x.
// square function definition
function square( y )
{
return y * y;
}
// -->
The return statement
</script>
</head><body></body>
</html>
passes the value of y * y
back to the calling function.
2001 Prentice Hall, Inc.
All rights reserved.
4
Outline
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Maximum.html
<!-- Fig. 10.3: maximum.html -->
<!-- Maximum function
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Finding the Maximum of Three
PromptValues</title>
for the user to input
three integers.
<script type = "text/javascript">
<!-var input1 =
window.prompt( "Enter first number", "0" );
var input2 =
window.prompt( "Enter second number", "0" );
var input3 =
window.prompt( "Enter third Call
number",
"0"maximum
);
function
and pass it the value
variables value1, value2 and value3.
input1of);
var value1 = parseFloat(
var value2 = parseFloat( input2 );
var value3 = parseFloat( input3 );
var maxValue = maximum( value1,
value2,
value3
Variables
x, y and
z get);
the
value of variables
value1, value2 and value3, respectively.
number: " + value1 +
document.writeln( "First
"<br />Second number: " + value2 +
"<br />Third number: " + value3Method
+
"<br />Maximum is: " + maxValue );
max returns the larger of the two
integers passed to it.
// maximum method definition (called from line 25)
function maximum( x, y, z )
{
return Math.max( x, Math.max( y, z ) );
2001 Prentice Hall, Inc.
All rights reserved.
6
36
37
38
39
40
41
42
43
44
}
// -->
</script>
</head>
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
</html>
Outline
Maximum.html
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
7
Outline
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
RandomInt.html
<!-- Fig. 10.4: RandomInt.html
-->
<!-- Demonstrating the Random method -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Shifted and Scaled Random Integers</title>
<script type = "text/javascript">
The for loop creates
<!-var value;
4 rows with 5 cells of a table.
Method floor rounds the number
document.writeln(
cell is
populated with a
"<table border = \"1\" width
= \"50%\">"
);Each
generated
by method
random
down.
document.writeln(
random number generated by
"<caption>Random Numbers</caption><tr>" );
method random.
for ( var i = 1; i <= 20; i++ ) {
value = Math.floor( 1 + Math.random() * 6 );
document.writeln( "<td>" + value + "</td>" );
// write end and start <tr> tags when
// i is a multiple of 5 and not 20
if ( i % 5 == 0 && i != 20 )
document.writeln( "</tr><tr>" );
}
document.writeln( "</tr></table>" );
// -->
</script>
</head>
2001 Prentice Hall, Inc.
All rights reserved.
9
36
37
38
39
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
</html>
Outline
RandomInt.html
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
RollDie.html
<!-- Fig. 10.5: RollDie.html -->
<!-- Rolling a Six-Sided Die -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Roll a Six-Sided Die 6000 Times</title>
This expression uses method random to
generate a random number between 1 and 6.
<script type = "text/javascript">
<!-var frequency1 = 0, frequency2 = 0,
frequency3 = 0, frequency4 = 0,
frequency5 = 0, frequency6 = 0, face;
When the controlling expression, face,
// summarize results
for ( var roll = 1; roll <= 6000;
++roll
) { label, the respective
matches
a case
face = Math.floor( 1 + Math.random()
* 6 variable
);
frequency
is incremented.
switch ( face ) {
case 1:
++frequency1;
break;
case 2:
++frequency2;
break;
case 3:
++frequency3;
break;
case 4:
++frequency4;
break;
case 5:
2001 Prentice Hall, Inc.
All rights reserved.
11
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
++frequency5;
break;
case 6:
++frequency6;
break;
}
}
Outline
The results of the dice beingRollDie.html
rolled 600 times
are displayed in a table.
document.writeln( "<table border = \"1\"" +
"width = \"50%\">" );
document.writeln( "<thead><th>Face</th>" +
"<th>Frequency<th></thead>" );
document.writeln( "<tbody><tr><td>1</td><td>" +
frequency1 + "</td></tr>" );
document.writeln( "<tr><td>2</td><td>" + frequency2
"</td></tr>" );
document.writeln( "<tr><td>3</td><td>" + frequency3
"</td></tr>" );
document.writeln( "<tr><td>4</td><td>" + frequency4
"</td></tr>" );
document.writeln( "<tr><td>5</td><td>" + frequency5
"</td></tr>" );
document.writeln( "<tr><td>6</td><td>" + frequency6
"</td></tr></tbody></table>" );
// -->
</script>
+
+
+
+
+
</head>
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
</html>
2001 Prentice Hall, Inc.
All rights reserved.
12
Outline
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Craps.html
<!-- Fig. 10.6: Craps.html -->
<!-- Craps Program
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Program that Simulates the Game of Craps</title>
<script type = "text/javascript">
<!-// variables used to test the state of the game
var WON = 0, LOST = 1, CONTINUE_ROLLING = 2;
// other variables used in program
var firstRoll = true,
// true if first roll
sumOfDice = 0,
// sum of the dice
If
the
value
of firstRoll is true,
myPoint = 0, // point if no win/loss on first roll
function rollDice
is called.
gameStatus = CONTINUE_ROLLING;
// game not
over yet
then
// process one roll of the dice
If function rollDice returns a value of
function play()
{
7 or 11, theplayer wins and the break
if ( firstRoll ) {
// first roll of the dice
statement causes program control
sumOfDice = rollDice();
proceeds to the first line after the switch
structure.
switch ( sumOfDice ) {
case 7: case 11:
// win on first roll
gameStatus = WON;
// clear point field
document.craps.point.value = "";
break;
case 2: case 3: case 12: // lose on first roll
2001 Prentice Hall, Inc.
All rights reserved.
14
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
Outline
gameStatus = LOST;
// clear point field
document.craps.point.value = "";
break;
Craps.html
default:
// remember point
If function rollDice retursn a 2, 3 or 12, the
gameStatus = CONTINUE_ROLLING;
myPoint = sumOfDice;
player loses and the break statement causes
document.craps.point.value = myPoint;
control to proceed to first line after the switch
firstRoll = false;
}
structure.
}
else {
sumOfDice = rollDice();
if ( sumOfDice == myPoint ) // win by making point
gameStatus = WON;
thevalue
valuereturned
of firstRoll
is false,
else
IfIfthe
by function
rollDice
if ( sumOfDice == 7 ) function
// loserollDice
by rollingis 7called to see if the
equals the value of variable myPoint, the player
gameStatus = LOST;
pointbecause
has been
wins
thereached.
point has been reached.
}
if ( gameStatus == CONTINUE_ROLLING )
window.status = "Roll again";
If the values returned by function
else {
rollDice equals 7, the player loses.
if ( gameStatus == WON )
window.status = "Player wins. " +
"Click Roll Dice to play again.";
else
window.status = "Player loses.
" + method status displays a
window
"Click Roll Dice to play again.";
message in the status bar of the browser.
firstRoll = true;
}
}
2001 Prentice Hall, Inc.
All rights reserved.
15
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
Outline
// roll the dice
function rollDice()
{
var die1, die2, workSum;
Craps.html
die1 = Math.floor( 1 +Function
Math.random()
* 6 is
);called to simulate
rollDice
die2 = Math.floor( 1 + Math.random() * 6 );
the rolling of two dice on the craps table.
workSum = die1 + die2;
document.craps.firstDie.value = die1;
document.craps.secondDie.value Methods
= die2; random and floor
document.craps.sum.value = workSum;
generate the values for the two
are used to
dice.
return workSum;
}
// -->
</script>
Referencing the names of form elements
in the XHTML document, the vlaues of
the dice are placed in their respective
form fields.
</head>
<body>
<form name = "craps" action = "">
<table border = "1">
<caption>Craps</caption>
<tr><td>Die 1</td>
<td><input name = "firstDie" type = "text" />
</td></tr>
<tr><td>Die 2</td>
<td><input name = "secondDie" type = "text" />
</td></tr>
<tr><td>Sum</td>
<td><input name = "sum" type = "text" />
</td></tr>
<tr><td>Point</td>
<td><input name = "point" type = "text" />
</td></tr>
2001 Prentice Hall, Inc.
All rights reserved.
16
106
107
108
109
110
111
<tr><td><input type = "button" value = "Roll Dice"
onclick = "play()" /></td></tr>
</table>
</form>
</body>
</html>
A text
XHTM L G UI
c om ponent
Outline
Craps.html
Program Output
A button
XHTM L G UI
c om ponent
Brow ser’ s
st at us ba r
2001 Prentice Hall, Inc.
All rights reserved.
17
Outline
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
18
Outline
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
19
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Scoping.html
<!-- Fig. 10.7: scoping.html
-->
<!-- Local and Global Variables -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
To begin the
<title>A Scoping Example</title>
<script type = "text/javascript">
<!-var x = 1;
// global variable
Function
Outline
program, variable x is initialized to 1.
start changes the value of x to 5.
function start()
{
var x = 5;
// variable local to function start
document.writeln( "local x in start is " + x );
functionA();
functionB();
functionA();
functionB();
//
//
//
//
functionA
has local
x
Function
functionA
changes
functionB uses global variable x
functionA reinitializes local x
global variable x retains its value
the value of x to 25.
document.writeln(
"<p>local x in start is " + x + "</p>" );
}
function functionA()
{
var x = 25; // initialized each time
// functionA is called
2001 Prentice Hall, Inc.
All rights reserved.
20
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
document.writeln( "<p>local x in functionA is " +
x + " after entering functionA" );
++x;
document.writeln( "<br />local x in functionA is " +
x + " before exiting functionA" + "</p>" );
}
Outline
Scoping.html
The value of x is incremented.
function functionB()
{
document.writeln( "<p>global variable x is " + x +
" on entering functionB" );
x *= 10;
document.writeln( "<br />global variable x is " +
x + " on exiting functionB" + "</p>" );
}
// -->
Function functionB multiplies the value
</script>
of x by 10.
</head>
<body onload = "start()"></body>
</html>
2001 Prentice Hall, Inc.
All rights reserved.
21
Outline
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
22
10.9 JavaScript Global Functions
Glob a l func tio n
De sc rip tio n
escape
This function takes a string argument and returns a string in which all spaces, punctuation,
accent characters and any other character that is not in the ASCII character set (see Appendix
C, ASCII Character Set) are encoded in a hexadecimal format (see the Number Systems
appendix) that can be represented on all platforms.
eval
This function takes a string argument representing JavaScript code to execute. The JavaScript
interpreter evaluates the code and executes it when the eval function is called. This function
allows JavaScript code to be stored as strings and executed dynamically.
isFinite
This function takes a numeric argument and returns true if the value of the argument is not
NaN, Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY; otherwise,
the function returns false.
isNaN
This function takes a numeric argument and returns true if the value of the argument is not a
number; otherwise, the function returns false. The function is commonly used with the return
value of parseInt or parseFloat to determine whether the result is a proper numeric
value.
Fig. 10.8
JavaScript g lob a l func tions.
2001 Prentice Hall, Inc. All rights reserved.
23
10.9 JavaScript Global Functions
Glob a l func tio n
De sc rip tio n
parseFloat
This function takes a string argument and attempts to convert the beginning of the string into a
floating-point value. If the conversion is unsuccessful, the function returns NaN; otherwise, it
returns the converted value (e.g., parseFloat( "abc123.45" ) returns NaN, and
parseFloat( "123.45abc" ) returns the value 123.45).
parseInt
This function takes a string argument and attempts to convert the beginning of the string into
an integer value. If the conversion is unsuccessful, the function returns NaN; otherwise, it
returns the converted value (e.g., parseInt( "abc123" ) returns NaN, and parseInt(
"123abc" ) returns the integer value 123). This function takes an optional second
argument, from 2 to 36, specifying the radix (or base) of the number. Base 2 indicates that
the first argument string is in binary format, base 8 indicates that the first argument string is
in octal format and base 16 indicates that the first argument string is in hexadecimal
format. See see the “Number Systems” appendix for more information on binary, octal and
hexadecimal numbers.
unescape
Fig. 10.8
This function takes a string as its argument and returns a string in which all characters
previously encoded with escape are decoded.
JavaScript g lob a l func tions.
2001 Prentice Hall, Inc. All rights reserved.
24
10.10 Recursion
Final value = 120
5!
5!
5 * 4!
4 * 3!
3 * 2!
2 * 1!
1
(a) Procession of recursive calls.
5! = 5 * 24 = 120 is returned
5 * 4!
4! = 4 * 6 = 24 is returned
4 * 3!
3! = 3 * 2 = 6 is returned
3 * 2!
2! = 2 * 1 = 2 is returned
2 * 1!
1 returned
1
(b) Values returned from each recursive call.
Fig. 10.9 Recursive evaluation of 5!.
2001 Prentice Hall, Inc. All rights reserved.
25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 10.10: FactorialTest.html -->
<!-- Recursive factorial example
-->
Outline
FactorialTest.ht
ml
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Recursive Factorial Function</title>
Calling function factorial and
passing it the value of i.
<script language = "javascript">
document.writeln( "<h1>Factorials of 1 to 10</h1>" );
document.writeln(
"<table border = '1' width = '100%'>" );
for ( var i = 0; i <= 10; i++ )
document.writeln( "<tr><td>" + i + "!</td><td>" +
factorial( i ) + "</td></tr>" );
Variable number gets the value of variable i.
document.writeln( "</table>" );
// Recursive definition of function factorial
function factorial( number )
{
Call to function factorial and passing
if ( number <= 1 ) // base case
less than the current value of number.
return 1;
else
return number * factorial( number - 1 );
}
</script>
</head><body></body>
</html>
it 1
2001 Prentice Hall, Inc.
All rights reserved.
26
Outline
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
27
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- Fig. 10.11: FibonacciTest.html -->
<!-- Recursive Fibonacci example
-->
Outline
FibonacciTest.ht
ml
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Recursive Fibonacci Function</title>
<script language = "javascript">
Convert from a string to an integer the value the
user typed into the number text field.
// Event handler for button XHTML component in myForm
function getFibonacciValue()
Display the number the user
{
var value = parseInt(
status bar.
document.myForm.number.value );
window.status =
"Calculating Fibonacci number for " + value;
document.myForm.result.value = fibonacci( value );
window.status = "Done calculating Fibonacci number";
}
entered in the
Display
the result
of thethat
calculation
// Recursive definition of The
function
status fibonacci
bar
displays
a message
the call in the
text field.
function fibonacci( n )
to function result
fibonacci
is complete.
{
if ( n == 0 || n == 1 ) // base case
return n;
else
return fibonacci( n - 1 ) + fibonacci( n - 2 );
Test for base case (n equal to 1 or 0).
}
</script>
</head>
Two recursive calls are made if n is greater than 1.
2001 Prentice Hall, Inc.
All rights reserved.
28
35
36
37
38
39
40
41
42
43
44
45
46
<body>
<form name = "myForm">
<table border = "1">
<tr><td>Enter an integer</td>
<td><input name = "number" type = "text"></td>
<td><input type = "button" value = "Calculate"
onclick = "getFibonacciValue()"</tr>
<tr><td>Fibonacci value</td>
<td><input name = "result" type = "text"></td></tr>
</table>
</form></body>
</html>
Outline
FibonacciTest.ht
ml
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
29
Outline
Program Output
2001 Prentice Hall, Inc.
All rights reserved.
30
10.11 Example Using Recursion: Fibonacci
Series
f( 3 )
return f( 2 )
return f( 1 )
return 1
+
+
f( 0 )
f( 1 )
return 1
return 0
Fig. 10.12 Set of recursive calls to function fibonacci.
2001 Prentice Hall, Inc. All rights reserved.
31
10.12 Recursion vs. Iteration
C ha p ter
Re c ursio n exa m p le s a nd exerc ise s
10
Factorial function
Greatest common divisor
Sum of two integers
Multiply two integers
Raising an integer to an integer power
Towers of Hanoi
Visualizing recursion
11
Sum the elements of an array
Print an array
Print an array backward
Check if a string is a palindrome
Minimum value in an array
Selection sort
Eight Queens
Linear search
Binary search
Quicksort
Maze traversal
12
Printing a string input at the keyboard backward
Fig. 10.13
Sum m a ry o f re c ursio n e xa m p le s a nd e xe rc ise s in the te xt.
2001 Prentice Hall, Inc. All rights reserved.
© Copyright 2026 Paperzz