JavaScript: Functions
Outline
Introduction
Program Modules in JavaScript
Programmer-Defined Functions
Function Definitions
Random-Number Generation
Example: Game of Chance
Another Example: Random Image Generator
Scope Rules
JavaScript Global Functions
Recursion
Recursion vs. Iteration
Introduction
Software design
Break software up
into modules
Easier to maintain and
debug
Divide and conquer
Program Modules in JavaScript
Modules in JavaScript
Functions
Methods
Belong to an object
JavaScript includes many useful pre-defined
methods
Combine with programmer-defined methods to
make a program
Program Modules in JavaScript
Functions
Started by function call
Receive necessary information via
arguments (parameters)
Boss-Worker relationship
Calling function
Called function
Return value when finished
Can have many tiers
Program Modules in JavaScript
worker4 worker5
Fig. 10.1 Hierarchical boss-function/worker-function relationship.
Program Modules in JavaScript
Function calls
Name
Left parenthesis
Arguments separated by commas
Constants, variables or expressions
Right parenthesis
Examples:
total += parseFloat( inputValue );
total += parseFloat( s1 + s2 );
Programmer-Defined Functions
Defining functions
All variables declared in function are called
local
Do not exist outside current function
Parameters
Also local variables
Promotes reusability
Keep short
Name clearly
Function Definitions
Format of a function definition
function function-name( parameter-list )
{
declarations and statements
}
Function name any valid identifier
Parameter list names of variables that will
receive arguments
Must have same number as function call
May be empty
Declarations and statements
Function body (“block” of code)
Function Definitions
Returning control
return statement
Can return either
nothing, or a value
return
expression;
No return
statement same as
return;
Function Definitions
Writing a function to square two
numbers
for loop from 1 to 10
Pass each number as argument to
square
return value of argument multiplied
by itself
Display result
Function Definitions
Function Definitions
Finding the maximum of 3 numbers
Prompt for 3 inputs
Convert to numbers
Pass to maximum
[Link]
Function Definitions
Function Definitions
Random-Number Generation
Random-number generation introduces
element of chance
[Link]
var randomValue = [Link]();
Floating point value between 0 and 1, but
not including 1.
Adjust range by scaling and shifting
[Link]
Always round down
[Link](1 + [Link]() *
Random-Number Generation
Random-Number Generation
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "[Link]
4
<!-- Fig. 10.5: [Link] -->
5
<!-- Rolling a Six-Sided Die -->
6
7
<html xmlns = "[Link]
8
<head>
9
<title>Roll a Six-Sided Die 6000 Times</title>
10
11
<script type = "text/javascript">
12
<!--
This expression uses method random to
13
var frequency1 = 0, frequency2 =
generate a random number between 1 and
14 0,6.
frequency3 = 0, frequency4 = 0,
15
frequency5 = 0, frequency6 = 0, face;
16
17
// summarize results
18
for ( var roll = 1; roll <= 6000; ++roll ) {
19
face = [Link]( 1 + [Link]() * 6 );
20
21
22 switch ( face ) {
23 case 1:
24 + When the controlling expression, face,
25 +frequency1; matches a case label, the respective
26 break; frequency variable is incremented.
27 case 2:
28 +
29 +frequency2;
30
31
break;
case 3: [Link]
l (2 of 3)
32 +
33 +frequency3;
34 break;
35 case 4:
36 +
37 +frequency4;
38 break;
39 case 5:
40 +
41 +frequency5;
}
42 break;
43 case 6:
+
+frequency6;
break;
}
44 [Link]( "<table border = \"1\"" +
45 "width = \"50%\">" ); The results of rolling the die
46 [Link]( "<thead><th>Face</th>" + 600 times are displayed in a
47 "<th>Frequency<th></thead>" );
table.
48 [Link]( "<tbody><tr><td>1</td><td>" +
49 frequency1 + "</td></tr>" );
50 [Link]( "<tr><td>2</td><td>" + frequency2
+
51
[Link]
"</td></tr>" );
52
[Link]( "<tr><td>3</td><td>" + frequency3 +
53
"</td></tr>" );
l (3 of 3)
54
[Link]( "<tr><td>4</td><td>" + frequency4 +
55
"</td></tr>" );
56
[Link]( "<tr><td>5</td><td>" + frequency5 +
57
"</td></tr>" );
58
[Link]( "<tr><td>6</td><td>" + frequency6 +
59
"</td></tr></tbody></table>" );
60
// -->
61
</script>
62
63 </head>
64 <body>
65 <p>Click Refresh (or Reload) to run the script again</p>
66 </body>
67 </html>
Random-Number Generation
Example: Game of Chance
Craps
Click Roll Dice
Text fields show rolls, sum and point
Status bar displays results
Example: Game of Chance
Uses XHTML forms
Gather multiple inputs at once
Empty action attribute
name attribute allows scripts
to interact with form
Event handling and event-driven programming
Assign a function to an event
Onclick
Constants
Variable that cannot be modified
Part of many languages, not supported in JavaScript
Name “constant” variables with all capital letters
Make values easier to remember/change
Example: Game of Chance
Changing properties
Access with dot (.) notation
value property of text fields
status property of window
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "[Link]
4
<!-- Fig. 10.6: [Link] -->
5
<!-- Craps Program -->
6
7
8 <html xmlns = "[Link]
9 <head>
10 <title>Program that Simulates the Game of Craps</title>
11
<script type = "text/javascript">
12
<!--
13
// variables used to test the state of the game
14
var WON = 0, LOST = 1, CONTINUE_ROLLING = 2;
15
16
// other variables used in program
17
var firstRoll = true, // true if first roll
18
sumOfDice = 0, // sum of the dice
19
myPoint = 0, // point if no win/loss on first roll
20
gameStatus = CONTINUE_ROLLING; // game not over yet
21
22
23 // process one roll of the dice
24 function play()
25 {
26 If the value of firstRoll is true, then
irst roll of the dice
if ( firstRoll ) {
27 sumOfDice = rollDice(); function is
rollDice
28 // f called.
If function rollDice returns a value of
29 switch ( sumOfDice ) {
7 or 11, the player wins and the break
30 case 7: case 11: // win on first
statement causes program control
roll
31 gameStatus = WON;
proceeds to the first line after the switch
32 // clear point field
structure.
33 [Link] = "";
34 break;
35 case 2: case 3: case 12: // lose on first roll
36 gameStatus = LOST;
37 // clear point field If function rollDice returns a 2, 3 or 12,
38 [Link] the player loses and the break statement
= "";
39 break; causes control to proceed to first line after
40 default: // the switch
emember pointstructure.
41 r
gameStatus = CONTINUE_ROLLING;
42 myPoint = sumOfDice;
43 [Link] = myPoint;
44 firstRoll = false;
45 }
46 }
47 else {
48 sumOfDice = rollDice();
49
if ( sumOfDice == myPoint ) // win by making point
50
51 gameStatus = WON; If the value of firstRoll is
52 else function
false , rollDice is called to see if
53 if ( sumOfDice == 7 ) // point
the by has
lose been reached.
rolling
7
54 gameStatus = LOST;
55 }
56
57 if ( gameStatus == CONTINUE_ROLLING )
If the values returned by function rollDice
58 [Link] = "Roll again";
equals 7, the player loses.
59 else {
60 if ( gameStatus == WON ) If the value returned by function rollDice
61 [Link] = "Player wins. " equals
+ the value of variable myPoint, the player
62 wins because the point has been reached.
"Click Roll Dice to play ag ain."
63 ;
else
64 [Link] = "Player loses. " +
65 "Click Roll Dice to play again.";
66
window method status displays a
67 firstRoll = true;
message in the status bar of the browser.
68 }
69 }
70
// roll the dice
71
function rollDice()
72
{
73
var die1, die2, workSum;
74
75 Function rollDice is called to simulate
76 die1 = [Link]( 1 the rolling of two
+ [Link]() * 6 dice
); on the craps
77 die2 = [Link]( 1 + table.
[Link]() * 6 );
78 workSum = die1 + die2;
79
80
81
[Link]
[Link] = di
e1;
Methods random and floor are used to
ie2;
l (4 of 5) generate the values for the two dice.
[Link] = d
82 [Link] = workSum;
83
84 return workSum;
85 } Referencing the names of form elements
86 // --> in the XHTML document, the values of
87 </script> the dice are placed in their respective
88 form fields.
89 </head>
90 <body>
91 <form name = "craps" action = "">
92 <table border = "1">
93 <caption>Craps</caption>
94 <tr><td>Die 1</td>
95 <td><input name = "firstDie" type = "text" />
96 </td></tr>
97 <tr><td>Die 2</td>
98
99 [Link]
<td><input name = "secondDie" type = "text" />
</td></tr>
l (5 of 5)
100 <tr><td>Sum</td>
101 <td><input name = "sum" type = "text" />
102 </td></tr>
103 <tr><td>Point</td>
104 <td><input name = "point" type = "text" />
105 </td></tr>
106 <tr><td><input type = "button" value = "Roll Dice"
107 /></td></tr>
108 </table>
109 </form>
110 </body>
111 </html>
Example: Game of Chance
A text XHTML GUI component
A button XHTML GUI component
Browser’s status bar
Example: Game of Chance
Example: Game of Chance
Another Example:
Random Image Generator
Randomly selecting an image
Images have integer names (i.e., [Link],
[Link], …, [Link])
Generate random number in proper range
Update src property
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "[Link]
4
<!-- Fig. 10.7: [Link] --
5
>
6
<!-- Randomly displays one of 7 images -->
7
ml">
Rando m
8
9
<html xmlns = "[Link]
<head> Inserting a random number into the image’s src
10 <title>Random Image Generator</titl property
e with
> [Link] and [Link]
11
12
13
[Link]
(1 of 1)
<script type = "text/javascript">
<!--
14 [Link] ( "<img src = \"" +
15 [Link]( 1 + [Link]() * 7 ) +
16 ".gif\" width = \"105\" height = \"100\" />" );
17 // -->
18 </script>
19
20 </head>
21
22 <body>
23 <p>Click Refresh (or Reload) to run the script again</p>
24 </body>
25 </html>
Another Example:
Random Image Generator
Scope Rules
Scope
Portion of program where identifier can be
referenced
Types of Scope:
Global
Local: inside function
• Identifiers exist only between opening and closing
braces
• Local variables hide global variables
Scope Rules
Scope demonstration
Global variable x initialized to 1
start has local variable x initialized to 5
functionA has local variable x initialized
to
25
functionB has no local variable x
Observe output of each function
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "[Link]
4
<!-- Fig. 10.8: [Link] --
5
>
6
<!-- Local and Global Variables -->
7
<html xmlns = "[Link]
8
<head>
9
<title>A Scoping Example</title>
10
To begin the program, variable x is initialized to 1.
11
<script type = "text/javascript">
12
<!--
13
var x = 1; // global variable
14
15 Function start changes the value of x to 5.
function start()
16
{
17
var x = 5; // variable local to function start
18
19
[Link]( "local x in start is " + x );
20
21
functionA(); // functionA has local x
22
functionB(); // functionB uses global variable x
23
functionA(); // functionA reinitializes local x
24
functionB(); // global variable x retains its
25
value
26
[Link](
27
"<p>local x in start is " + x + "</p>" );
28
}
29
30
function functionA()
31
{
32
var x = // initialized each time
33
[Link]
25;
// functionA is called
34
35
36 [Link]( "<p>loc al x in functionA is "
+ Function functionA changes the value of x to 25.
37
38
39
++x; (2 of 3)
x + " after entering functionA" );
[Link]( "<br />local x in functionA is " +
40 x + " before exiting functionA" + "</p>" ) ;
The value of x is incremented.
41 }
42
43 function functionB()
44 {
45 [Link]( "<p>global variable x is " + x +
46 " on entering functionB" );
47 x *= 10;
48 [Link]( "<br />global variable x is " +
x + " on exiting functionB" + "</p>" );
49
50
} Function functionB multiplies the value of x by 10.
51
52
// -->
</script> [Link]
(3 of 3)
53
54 </head>
55 <body >56 </html>
Scope Rules
JavaScript Global Functions
Global object
• Always available
• Provides 7 methods
• Do not need to explicitly reference
Global before method call
• Also holds all global variables, user
defined functions
Recursion
Recursive functions
Call themselves
Part of return statement
Must have base case
Simplest case of problem
Returns value rather than calling itself
Each recursive call simplifies input
When simplified to base case, functions return
Recursion
Factorials
Product of calculation n · (n - 1) · (n - 2) · … · 1
Iterative approach:
var factorial = 1;
for (var counter = number; counter >= 1; --counter)
factorial *= counter;
Note each factor is one less than previous
factor
Stops at 1: base case
Perfect candidate for recursive solution
Recursion
Final value = 120
5! 5!
5! = 5 * 24 = 120 is returned
5 * 4! 5 * 4!
4! = 4 * 6 = 24 is returned
4 * 3! 4 * 3!
3! = 3 * 2 = 6 is returned
3 * 2! 3 * 2!
2! = 2 * 1 = 2 is returned
2 * 1! 2 * 1!
1 returned
1 1
(a) Procession of (b) Values returned from each recursive
recursive calls. call.
Fig. 10.10 Recursive evaluation of 5!.
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "[Link]
4
5 <!-- Fig. 10.11: [Link] -->
6 <!-- Recursive factorial example -->
7
8 <html xmlns = "[Link]
9 <head>
10 <title>Recursive Factorial Function</title>
11
<script language = "javascript">
12 Calling function factorial and
[Link]( "<h1>Factorials of 1 to 10</h1>" );
13 passing it the value of i.
[Link](
14
"<table border = '1' width = '100%'>" );
15
16
for ( var i = 0; i <= 10; i++ )
17
[Link]( "<tr><td>" + i + "!</td><td>" +
18
factorial( i ) + "</td></tr>" );
19
20
[Link]( "</table>" );
21
22
23 // Recursive definition of function factorial
24
function factorial( number ) Variable number gets the value of variable i.
{
25
26 if ( number <= 1 ) // base casCall to function factorial and passing it 1
e
27 return less than the current value of number .
1;
28 els
29 e
return number * factorial( number - 1 );
30 }
31 </script>
32 </head><body></body>
33 </html>
Recursion
Example of Using Recursion:
The Fibonacci Series
GUI input setup:
All user inputs (if
there are any) are
defined by HTML
INPUT tag
<INPUT NAME =
“inputName”
TYPE =
“text”>
Enter as many inputs as you want, giving each an
applicable name
The form button component allows the user to send his
inputted information to the server
Example of Using Recursion:
The Fibonacci Series (II)
Fibonacci series:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89…
Begins with 0 and 1
Each number is sum of pervious two numbers
May be defined recursively as:
fibonacci( 0 ) = 0
fibonacci( 1 ) = 1
fibonacci( n ) = fibonacci( n - 1 ) + fibonacci( n - 2)
Avoid programs with Fibonacci-style calls
Results in exponential “explosion” of calls
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2 <HTML>
3<!-- Fig. 11.10: [Link] -->
4
5 <HEAD>
6<TITLE>Recursive Fibonacci Function</TITLE>
7
8 <SCRIPT LANGUAGE = "JavaScript">
9 // Event handler for button HTML
component in myForm
10function getFibonacciValue() 11
{
12 var value =
parseInt( [Link]
.[Link] );
13 [Link] =
14 "Calculating Fibonacci
number for " + value;
15 [Link]
// Recursive definition of function fibonacci
lue = fibonacci( value );
function fibonacci( n )
[Link] = "Done calculating Fibonacci number"; 17 }
{
18
19 if ( n == 0 || n == 1 ) // base case
20 return n;
21 else
22 return fibonacci( n - 1 ) + fibonacci( n - 2 );
23
24
25
26 }
27 </SCRIPT>
28
29 </HEAD>
31<BODY>
32<FORM NAME = "myForm">
33 <TABLE BORDER = "1">
34 <TR><TD>Enter an integer</TD>
35 <TD><INPUT NAME = "number" TYPE = "text"></TD>
36 <TD><INPUT TYPE = "button" VALUE = "Calculate"
37 >38 <TR><TD>Fibonacci value</TD>
39 <TD><INPUT NAME = "result" TYPE = "text"></TD></TR>
40</TABLE>
41</FORM></BODY>
42</HTML>
Script Outputs:
Example of Using Recursion: The Fibonacci Series
Set of Recursive Calls to Function fibonacci
f( 3 )
return
f( 2 ) + f( 1 )
return f( 0 ) return 1
f( 1 ) +
return 1 return 0
Recursion vs. Iteration
Iteration
Explicitly uses repetition structures to achieve
result
Terminates when loop-continuation condition
fails
Often faster than recursion
Recursion
Repeats through function calls
Terminates when base case reached
Slower due to function call overhead
Each call generates new copy of local variables
Easy to read and debug when modeling problem