0% found this document useful (0 votes)
24 views

Ch9 Functions

JS_Function
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Ch9 Functions

JS_Function
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 74

1

JavaScript: Functions

 2008 Pearson Education, Inc. All rights reserved.


2

Form ever follows function.


—Louis Sullivan
E pluribus unum.
(One composed of many.)
—Virgil
O! call back yesterday, bid time return.
—William Shakespeare
Call me Ishmael.
—Herman Melville
When you call me that, smile.
—Owen Wister

 2008 Pearson Education, Inc. All rights reserved.


3

OBJECTIVES
In this chapter you will learn:
 To construct programs modularly from
small pieces called functions.
 To create new functions.
 How to pass information between
functions.
 Simulation techniques that use random
number generation.
 How the visibility of identifiers is limited to
specific regions of programs.

 2008 Pearson Education, Inc. All rights reserved.


4

9.1 Introduction
9.2 Program Modules in JavaScript
9.3 Programmer-Defined Functions
9.4 Function Definitions
9.5 Random Number Generation
9.6 Example: Game of Chance
9.7 Another Example: Random Image Generator
9.8 Scope Rules
9.9 JavaScript Global Functions
9.10 Recursion
9.11 Recursion vs. Iteration
9.12 Wrap-Up
9.13 Web Resources

 2008 Pearson Education, Inc. All rights reserved.


5

9.1 Introduction

• To develop and maintain a large program


– construct it from small, simple pieces
– divide and conquer

 2008 Pearson Education, Inc. All rights reserved.


6

9.2 Program Modules in JavaScript


• JavaScript programs are written by combining
new functions that the programmer writes with
“prepackaged” functions and objects available in
JavaScript
• The term method implies that a function belongs
to a particular object
• We refer to functions that belong to a particular
JavaScript object as methods; all others are
referred to as functions.

 2008 Pearson Education, Inc. All rights reserved.


7

9.2 Program Modules in JavaScript


(Cont.)
• JavaScript provides several objects that have a rich
collection of methods for performing common
mathematical calculations, string manipulations, date and
time manipulations, and manipulations of collections of
data called arrays.
• Whenever possible, use existing JavaScript objects,
methods and functions instead of writing new ones. This
reduces script-development time and helps avoid
introducing errors.

 2008 Pearson Education, Inc. All rights reserved.


8

Good Programming Practice 9.1

Familiarize yourself with the rich collection of


objects and methods provided by JavaScript.

 2008 Pearson Education, Inc. All rights reserved.


9

Software Engineering Observation 9.1

Avoid reinventing the wheel. Use existing


JavaScript objects, methods and functions
instead of writing new ones. This reduces
script-development time and helps avoid
introducing errors.

 2008 Pearson Education, Inc. All rights reserved.


10

Portability Tip 9.1

Using the methods built into JavaScript


objects helps make scripts more portable.

 2008 Pearson Education, Inc. All rights reserved.


11

9.2 Program Modules in JavaScript


(Cont.)
• You can define programmer-defined functions that
perform specific tasks and use them at many points in a
script
– The actual statements defining the function are written only once and
are hidden from other functions
• Functions are invoked by writing the name of the
function, followed by a left parenthesis, followed by a
comma-separated list of zero or more arguments, followed
by a right parenthesis
• Methods are called in the same way as functions, but
require the name of the object to which the method
belongs and a dot preceding the method name
• Function (and method) arguments may be constants,
variables or expressions

 2008 Pearson Education, Inc. All rights reserved.


12

boss is boss of all workers

Worker1 is boss of
worker4 and worker5

worker1, worker2 and


worker3 report back to
Worker4 and worker5 boss
report back to worker1

Fig. 9.1 | Hierarchical boss-function/worker-function relationship.

 2008 Pearson Education, Inc. All rights reserved.


13

9.3 Programmer-Defined Functions

• Variables declared in function definitions are


local variables
– they can be accessed only in the function in which they are
defined
• A function’s parameters are considered to be
local variables
• When a function is called, the arguments in the
call are assigned to the corresponding parameters
in the function definition

 2008 Pearson Education, Inc. All rights reserved.


14

9.3 Programmer-Defined Functions


(Cont.)
• Code that is packaged as a function can be
executed from several locations in a program by
calling the function.
• Each function should perform a single, well-
defined task, and the name of the function should
express that task effectively
– Promotes software reusability

 2008 Pearson Education, Inc. All rights reserved.


15

Software Engineering Observation 9.2

If a function’s task cannot be expressed


concisely, perhaps the function is performing
too many different tasks. It is usually best to
break such a function into several smaller
functions.

 2008 Pearson Education, Inc. All rights reserved.


16

9.4 Function Definitions


• return statement
– passes information from inside a function back to the point in the
program where it was called
• A function must be called explicitly for the code in its
body to execute
• The format of a function definition is
function function-name( parameter-list )
{
declarations and statements
}

 2008 Pearson Education, Inc. All rights reserved.


17

9.4 Function Definitions (Cont.)


• Three ways to return control to the point at
which a function was invoked
– Reaching the function-ending right brace
– Executing the statement return;
– Executing the statement “return expression;” to
return the value of expression to the caller
• When a return statement executes, control
returns immediately to the point at which the
function was invoked

 2008 Pearson Education, Inc. All rights reserved.


1 <?xml version = "1.0" encoding = "utf-8"?> 18
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Fig. 9.2 |
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 Programmer-
5 <!-- Fig. 9.2: SquareInt.html --> defined function
6 <!-- Programmer-defined function square. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
square (Part 1
8 <head> of 2).
9 <title>A Programmer-Defined square Function</title>
10 <script type = "text/javascript">
11 <!--
12 document.writeln( "<h1>Square the numbers from 1 to 10</h1>" );
13
14 // square the numbers from 1 to 10
15 for ( var x = 1; x <= 10; x++ )
16 document.writeln( "The square of " + x + " is " +
17 square( x ) + "<br />" );
18
19 // The following square function definition is executed
20 // only when the function is explicitly called.
21
22 // square function definition Calls function square with x as
23 function square( y ) an argument, which will return the
24 {
value to be inserted here
25 return y * y;
26 } // end function square
27 // -->
Begin function square
28 </script> Names the parameter y
End function square Returns the value of y * y
29 </head><body></body>
30 </html> (the argument squared) to the
caller  2008 Pearson Education,
Inc. All rights reserved.
19

Fig. 9.2 | Programmer-defined function square (Part 2 of 2).

 2008 Pearson Education, Inc. All rights reserved.


20

Common Programming Error 9.1

Using the JavaScript var keyword to declare


a variable in a function parameter list results
in a JavaScript runtime error.

 2008 Pearson Education, Inc. All rights reserved.


21

Good Programming Practice 9.2

Place a blank line between function


definitions to separate the functions and
enhance program readability.

 2008 Pearson Education, Inc. All rights reserved.


22

Software Engineering Observation 9.3

Statements that are enclosed in the body of a


function definition are not executed by the
Java-Script interpreter unless the function is
invoked explicitly.

 2008 Pearson Education, Inc. All rights reserved.


23

Common Programming Error 9.2

Forgetting to return a value from a function


that is supposed to return a value is a logic
error.

 2008 Pearson Education, Inc. All rights reserved.


24

Common Programming Error 9.3

Placing a semicolon after the right parenthesis


enclosing the parameter list of a function
definition results in a JavaScript runtime
error.

 2008 Pearson Education, Inc. All rights reserved.


25

Common Programming Error 9.4

Redefining a function parameter as a local


variable in the function is a logic error.

 2008 Pearson Education, Inc. All rights reserved.


26

Common Programming Error 9.5

Passing to a function an argument that is not


compatible with the corresponding
parameter’s expected type is a logic error and
may result in a JavaScript runtime error.

 2008 Pearson Education, Inc. All rights reserved.


27

Good Programming Practice 9.3

Although it is not incorrect to do so, do not


use the same name for an argument passed to
a function and the corresponding parameter
in the function definition. Using different
names avoids ambiguity.

 2008 Pearson Education, Inc. All rights reserved.


28

Software Engineering Observation 9.4

To promote software reusability, every


function should be limited to performing a
single, well-defined task, and the name of the
function should express that task effectively.
Such functions make programs easier to
write, debug, maintain and modify.

 2008 Pearson Education, Inc. All rights reserved.


29

Error-Prevention Tip 9.1

A small function that performs one task is


easier to test and debug than a larger function
that performs many tasks.

 2008 Pearson Education, Inc. All rights reserved.


1 <?xml version = "1.0" encoding = "utf-8"?> 30
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2
Fig. 9.3 |
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 Programmer-
5 <!-- Fig. 9.3: maximum.html --> defined maximum
6 <!-- Programmer-Defined maximum function. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
function (Part 1
8 <head> of 3).
9 <title>Finding the Maximum of Three Values</title>
10 <script type = "text/javascript">
11 <!--
12 var input1 = window.prompt( "Enter first number", "0" );
13 var input2 = window.prompt( "Enter second number", "0" );
14 var input3 = window.prompt( "Enter third number", "0" );
15
16 var value1 = parseFloat( input1 );
17 var value2 = parseFloat( input2 ); Creates integer values from
18 var value3 = parseFloat( input3 ); user input
19

 2008 Pearson Education,


Inc. All rights reserved.
20 var maxValue = maximum( value1, value2, value3 ); 31
21
Fig. 9.3 |
22 document.writeln( "First number: " + value1 +
Variable "<br />Second number: " + value2 + Programmer-
23
maxValue"<br />Third number: " + value3 + Calls function maximum
24
with arguments value1, defined maximum
25 stores the "<br />Maximum is: " + maxValue );
value2 and value3 function (Part 2
26 return value
27 of the call
// to
maximum function definition (called from line 20) of 3).
28 maximum function maximum( x, y, z )
Begin function maximum with
29 {
30 return Math.max( x, Math.max( y, z ) );
local variables x, y and z
31 } // end function maximum
// -->
32
Calls the Math object’s method
33 </script>
End function maximum max to compare the first variable
34 </head>
35 <body>
with the maximum of the other two
36 <p>Click Refresh (or Reload) to run the script again</p>
37 </body>
38 </html>

 2008 Pearson Education,


Inc. All rights reserved.
32

Fig. 9.3 | Programmer-defined maximum function (Part 3 of 3).


 2008 Pearson Education, Inc. All rights reserved.
33

9.5 Random Number Generation


• Method random generates a floating-point value from 0.0
up to, but not including, 1.0
• Random integers in a certain range can be generated by
scaling and shifting the values returned by random, then
using Math.floor to convert them to integers
– The scaling factor determines the size of the range (i.e. a scaling factor
of 4 means four possible integers)
– The shift number is added to the result to determine where the range
begins (i.e. shifting the numbers by 3 would give numbers between 3 and
7)
• Method Math.floor rounds its argument down to
the closest integer

 2008 Pearson Education, Inc. All rights reserved.


1 <?xml version = "1.0" encoding = "utf-8"?> 34
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Fig. 9.4 |
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 Random
5 <!-- Fig. 9.4: RandomInt.html --> integers, shifting
6 <!-- Random integers, shifting and scaling. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
and scaling
8 <head> (Part 1 of 2).
9 <title>Shifted and Scaled Random Integers</title>
10 <style type = "text/css">
11 table { width: 50%;
12 border: 1px solid gray;
13 text-align: center }
14 </style>
15 <script type = "text/javascript">
16 <!--
17 var value;
Shifts the range of Scales the range of return values
18
return values up by 1 by a factor of 6
19 document.writeln( "<table>" );
20 document.writeln( "<caption>Random Numbers</caption><tr>" ); Takes the floor of the number
21 from 1.0 up to, but not
22 for ( var i = 1; i <= 20; i++ ) including, 7.0
23 {
24 value = Math.floor( 1 + Math.random() * 6 );
25 document.writeln( "<td>" + value + "</td>" );
26
27 // start a new table row every 5 entries
28 if ( i % 5 == 0 && i != 20 )
29 document.writeln( "</tr><tr>" );
30 } // end for
 2008 Pearson Education,
31
Inc. All rights reserved.
32 document.writeln( "</tr></table>" ); 35
// -->
33
Fig. 9.4 |
34 </script>
35 </head> Random
36 <body> integers, shifting
37 <p>Click Refresh (or Reload) to run the script again</p>
38 </body>
and scaling
39 </html> (Part 2 of 2).

Variable value has a value from


1 to 6

 2008 Pearson Education,


Inc. All rights reserved.
1 <?xml version = "1.0" encoding = "utf-8"?> 36
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Fig. 9.5 | Rolling
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 a six-sided die
5 <!-- Fig. 9.5: RollDie.html --> 6000 times (Part
6 <!-- Rolling a Six-Sided Die 6000 times. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
1 of 3).
8 <head>
9 <title>Roll a Six-Sided Die 6000 Times</title>
10 <script type = "text/javascript">
11 <!--
12 var frequency1 = 0;
13 var frequency2 = 0;
14 var frequency3 = 0;
15 var frequency4 = 0;
16 var frequency5 = 0;
17 var frequency6 = 0;
18 var face;
19
20 // roll die 6000 times and accumulate results
21 for ( var roll = 1; roll <= 6000; roll++ ) Stores a random integer in the
22 { range 1 – 6 to variable face
23 face = Math.floor( 1 + Math.random() * 6 );
24
25 switch ( face )
Uses a switch statement to
26 { process the results
27 case 1:
28 ++frequency1;
29 break;

 2008 Pearson Education,


Inc. All rights reserved.
30 case 2: 37
++frequency2;
31
Fig. 9.5 | Rolling
32 break;
33 case 3: a six-sided die
34 ++frequency3; 6000 times (Part
35 break;
36 case 4:
2 of 3).
37 ++frequency4;
38 break;
39 case 5:
40 ++frequency5;
41 break;
42 case 6:
43 ++frequency6;
44 break;
45 } // end switch
46 } // end for Outputs the number of
47 occurrences of each face
48 document.writeln( "<table border = \"1\">" ); being rolled
49 document.writeln( "<thead><th>Face</th>" +
50 "<th>Frequency</th></thead>" );
51 document.writeln( "<tbody><tr><td>1</td><td>" +
52 frequency1 + "</td></tr>" );
53 document.writeln( "<tr><td>2</td><td>" + frequency2 +
54 "</td></tr>" );
55 document.writeln( "<tr><td>3</td><td>" + frequency3 +
56 "</td></tr>" );
57 document.writeln( "<tr><td>4</td><td>" + frequency4 +
58 "</td></tr>" );
 2008 Pearson Education,
Inc. All rights reserved.
59 document.writeln( "<tr><td>5</td><td>" + frequency5 + 38
60 "</td></tr>" );
Fig. 9.5 | Rolling
61 document.writeln( "<tr><td>6</td><td>" + frequency6 +
62 "</td></tr></tbody></table>" ); a six-sided die
63 // --> 6000 times (Part
64 </script>
65 </head>
3 of 3).
66 <body>
67 <p>Click Refresh (or Reload) to run the script again</p>
68 </body>
69 </html>

Running the script another time calls


Math.random again and (usually)
results in different frequencies
 2008 Pearson Education,
Inc. All rights reserved.
39

9.6 Example: Game of Chance


• JavaScript can execute actions in response to the user’s
interaction with a GUI component in an XHTML form.
This is referred to as GUI event handling
• An XHTML element’s onclick attribute indicates the
action to take when the user of the XHTML document
clicks on the element
• In event-driven programming
– the user interacts with a GUI component
– the script is notified of the event
– the script processes the event
• The user’s interaction with the GUI “drives” the
program.
• The function that is called when an event occurs is known
as an event-handling function or event handler.

 2008 Pearson Education, Inc. All rights reserved.


40

9.6 Example: Game of Chance (Cont.)

• The getElementById method, given an id as


an argument, finds the XHTML element with a
matching id attribute and returns a JavaScript
object representing the element
• The value property of a JavaScript object
representing an XHTML text input element
specifies the text to display in the text field
• An XHTML container (e.g. div, span, p)
element’s innerHTML property can be used in a
script to set the contents of the element

 2008 Pearson Education, Inc. All rights reserved.


1 <?xml version = "1.0" encoding = "utf-8"?> 41
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2
Fig. 9.6 | Craps
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 game simulation
5 <!-- Fig. 9.6: Craps.html --> (Part 1 of 6).
6 <!-- Craps game simulation. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Program that Simulates the Game of Craps</title>
10 <style type = "text/css">
11 table { text-align: right }
12 body { font-family: arial, sans-serif }
13 div.red { color: red }
14 </style>
15 <script type = "text/javascript">
16 <!--
17 // variables used to test the state of the game
18 var WON = 0;
19 var LOST = 1;
20 var CONTINUE_ROLLING = 2;
21
22 // other variables used in program
23 var firstRoll = true; // true if current roll is first
24 var sumOfDice = 0; // sum of the dice
25 var myPoint = 0; // point if no win/loss on first roll
26 var gameStatus = CONTINUE_ROLLING; // game not over yet
27
28 // process one roll of the dice
29 function play()
30 {  2008 Pearson Education,
Inc. All rights reserved.
31 // get the point field on the page 42
var point = document.getElementById( "pointfield" );
32
Fig. 9.6 | Craps
33
34 // get the status div on the page game simulation
35 var statusDiv = document.getElementById( "status" ); (Part 2 of 6).
36 if ( firstRoll ) // first roll of the dice
37 { statusDiv holds the object
38 sumOfDice = rollDice(); with “status” as its id
39
40 switch ( sumOfDice )
switch statement performs
41 {
42 case 7: case 11: // win on first roll
actions for specific dice values
43 gameStatus = WON;
44 // clear point field
45 point.value = "";
46 break;
47 case 2: case 3: case 12: // lose on first roll
48 gameStatus = LOST;
49 // clear point field
50 point.value = "";
51 break;
52 default: // remember point
53 gameStatus = CONTINUE_ROLLING;
54 myPoint = sumOfDice;
55 point.value = myPoint;
56 firstRoll = false;
57 } // end switch
58 } // end if
59 else
60 {  2008 Pearson Education,
Inc. All rights reserved.
61 sumOfDice = rollDice(); 43
62
Fig. 9.6 | Craps
63 if ( sumOfDice == myPoint ) // win by making point
64 gameStatus = WON; game simulation
65 else (Part 3 of 6).
66 if ( sumOfDice == 7 ) // lose by rolling 7
67 gameStatus = LOST;
68 } // end else
69
70 if ( gameStatus == CONTINUE_ROLLING )
71 statusDiv.innerHTML = "Roll again"; Sets the contents of the
72 else statusDiv object to “Roll
73 { Again”
74 if ( gameStatus == WON )
75 statusDiv.innerHTML = "Player wins. " +
Sets the contents of the statusDiv
76 "Click Roll Dice to play again.";
object to “Player wins. Click
77 else
78 statusDiv.innerHTML = "Player loses. " +
Roll Dice to play again.”
79 "Click Roll Dice to play again.";
80
Sets the contents of the
81 firstRoll = true;
statusDiv object to “Player
82 } // end else loses. Click Roll Dice
83 } // end function play to play again.”
84
85 // roll the dice
86 function rollDice()
87 {
88 var die1;
89 var die2;
90 var workSum;  2008 Pearson Education,
91 Inc. All rights reserved.
92 die1 = Math.floor( 1 + Math.random() * 6 ); 44
die2 = Math.floor( 1 + Math.random() * 6 );
93
Fig. 9.6 | Craps
94 workSum = die1 + die2;
95 game simulation
96 document.getElementById( "die1field" ).value = die1; (Part 4 of 6).
97 document.getElementById( "die2field" ).value = die2;
98 document.getElementById( "sumfield" ).value = workSum;
99
100 return workSum;
101 } // end function rollDice
102 // --> Sets the id fields of these container Sets the values of the
103 </script> objects so that they can be retrieved
104 </head>
die1field, die2field and
by getElementById in the script sumfield objects to die1,
105 <body>
106 <form action = ""> die2 and workSum, respectively
107 <table>
108 <caption>Craps</caption>
109 <tr><td>Die 1</td>
110 <td><input id = "die1field" type = "text" />
111 </td></tr>
112 <tr><td>Die 2</td>
113 <td><input id = "die2field" type = "text" />
114 </td></tr>
115 <tr><td>Sum</td>
116 <td><input id = "sumfield" type = "text" />
117 </td></tr>
118 <tr><td>Point</td>
119 <td><input id = "pointfield" type = "text" />
120 </td></tr>
 2008 Pearson Education,
Inc. All rights reserved.
121 <tr><td /><td><input type = "button" value = "Roll Dice" 45
onclick = "play()" /></td></tr>
122
Fig. 9.6 | Craps
123 </table>
124 <div id = "status" class = "red"> game simulation
125 Click the Roll Dice button to play</div> When the Roll Dice (Part 5 of 6).
126 </form> button is clicked,
127 </body> function play is called
128 </html>

 2008 Pearson Education,


Inc. All rights reserved.
46
Fig. 9.6 | Craps
game simulation
(Part 6 of 6).

 2008 Pearson Education,


Inc. All rights reserved.
47

Good Programming Practice 9.4

Use only uppercase letters (with underscores


between words) in the names of variables that
should be used as constants. This format
makes such variables stand out in a program.

 2008 Pearson Education, Inc. All rights reserved.


48

Good Programming Practice 9.5

Use meaningfully named variables rather


than literal values (such as 2) to make
programs more readable.

 2008 Pearson Education, Inc. All rights reserved.


49

Software Engineering Observation 9.5

Variables that are declared inside the body of


a function are known only in that function. If
the same variable names are used elsewhere in
the program, they will be entirely separate
variables in memory.

 2008 Pearson Education, Inc. All rights reserved.


50

Error-Prevention Tip 9.2

Initializing variables when they are declared


in functions helps avoid incorrect results and
interpreter messages warning of uninitialized
data.

 2008 Pearson Education, Inc. All rights reserved.


51

9.7 Another Example: Random Image


Generator
• We can use random number generation to
randomly select from a number of images in
order to display a random image each time a page
loads

 2008 Pearson Education, Inc. All rights reserved.


1 <?xml version = "1.0" encoding = "utf-8"?> 52
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2
Fig. 9.7 |
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 Random image
5 <!-- Fig. 9.7: RandomPicture.html --> generation
6 <!-- Random image generation using Math.random. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
using
8 <head> Math.random.
9 <title>Random Image Generator</title>
10 <script type = "text/javascript"> Creates an src attribute by
11 <!-- concatenating a random integer
12 document.write ( "<img src = \"" + from 1 to 7 with “.gif\” to
13 Math.floor( 1 + Math.random() * 7 ) + ".gif\" />" ); reference one of the images
14 // -->
1.gif, 2.gif, 3.gif, 4.gif,
15 </script>
5.gif, 6.gif or 7.gif
16 </head>
17 <body>
18 <p>Click Refresh (or Reload) to run the script again</p>
19 </body>
20 </html>

 2008 Pearson Education,


Inc. All rights reserved.
53

9.8 Scope Rules

• Each identifier in a program has a scope


• The scope of an identifier for a variable or
function is the portion of the program in which
the identifier can be referenced
• Global variables or script-level are accessible in
any part of a script and are said to have global
scope
– Thus every function in the script can potentially use the
variables

 2008 Pearson Education, Inc. All rights reserved.


54

9.8 Scope Rules (Cont.)


• Identifiers declared inside a function have
function (or local) scope and can be used only in
that function
• Function scope begins with the opening left brace
({) of the function in which the identifier is
declared and ends at the terminating right brace
(}) of the function
• Local variables of a function and function
parameters have function scope
• If a local variable in a function has the same
name as a global variable, the global variable is
“hidden” from the body of the function.

 2008 Pearson Education, Inc. All rights reserved.


55

Good Programming Practice 9.6

Avoid local-variable names that hide global-


variable names. This can be accomplished by
simply avoiding the use of duplicate identifiers
in a script.

 2008 Pearson Education, Inc. All rights reserved.


56

9.8 Scope Rules (Cont.)

•onload property of the body element calls an


event handler when the <body> of the XHTML
document is completely loaded into the browser
window

 2008 Pearson Education, Inc. All rights reserved.


1 <?xml version = "1.0" encoding = "utf-8"?> 57
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Fig. 9.8 |
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 Scoping
5 <!-- Fig. 9.8: scoping.html --> example (Part 1
6 <!-- Scoping example. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
of 3).
8 <head>
9 <title>A Scoping Example</title>
10 <script type = "text/javascript">
11 <!--
12 var x = 1; // global variable Global variable declaration
13
14 function start()
Local variable in
15 {
function start
16 var x = 5; // variable local to function start
17
18 document.writeln( "local x in start is " + x );
19
20 functionA(); // functionA has local x
21 functionB(); // functionB uses global variable x
22 functionA(); // functionA reinitializes local x
23 functionB(); // global variable x retains its value
24
25 document.writeln(
26 "<p>local x in start is " + x + "</p>" );
27 } // end function start
28

 2008 Pearson Education,


Inc. All rights reserved.
29 function functionA() 58
30 { Local variable in function Fig. 9.8 |
31 var x = 25; // initialized each time functionA, initialized each
32 // functionA is called
time functionA is called
Scoping
33 example (Part 2
34 document.writeln( "<p>local x in functionA is " +
35 x + " after entering functionA" );
of 3).
36 ++x;
37 document.writeln( "<br />local x in functionA is " +
38 x + " before exiting functionA" + "</p>" );
39 } // end functionA
40
41 function functionB()
42 {
43 document.writeln( "<p>global variable x is " + x +
44 " on entering functionB" );
45 x *= 10;
46 document.writeln( "<br />global variable x is " +
47 x + " on exiting functionB" + "</p>" );
48 } // end functionB
49 // -->
50 </script>
51 </head>
52 <body onload = "start()"></body> Calls function start when the body of
53 </html> the document has loaded into the
browser window

 2008 Pearson Education,


Inc. All rights reserved.
59

Fig. 9.8 | Scoping example (Part 3 of 3).

 2008 Pearson Education, Inc. All rights reserved.


60

9.9 JavaScript Global Functions

• JavaScript provides seven global functions as


part of a Global object
• This object contains
– all the global variables in the script
– all the user-defined functions in the script
– all the built-in global functions listed in the following slide
• You do not need to use the Global object
directly; JavaScript uses it for you

 2008 Pearson Education, Inc. All rights reserved.


61
Global Description
function Fig. 9.9 |
escape Takes a string argument and returns a string in which all spaces, punctuation, accent characters and JavaScript
any other character that is not in the ASCII character set (see Appendix D, ASCII Character Set) are
encoded in a hexadecimal format (see Appendix E, Number Systems) that can be represented on all global
platforms.
functions.
eval 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. [Note: It is considered a serious security risk to use
eval to process any data entered by a user because a malicious user could exploit this to run
dangerous code.]

isFinite Takes a numeric argument and returns true if the value of the argument is not NaN,
Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY (values that are not
numbers or numbers outside the range that JavaScript supports)—otherwise, the function returns
false.
isNaN Takes a numeric argument and returns true if the value of the argument is not a number;
otherwise, it 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.

parseFloat 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 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 Appendix E, Number Systems, for more information on binary, octal and
hexadecimal numbers.

unescape Takes a string as its argument and returns a string in which all characters previously encoded with
 2008 Pearson Education,
escape are decoded.
Inc. All rights reserved.
62

9.10 Recursion
• A recursive function calls itself, either directly, or
indirectly through another function.
• A recursive function knows how to solve only the simplest
case, or base case
– If the function is called with a base case, it returns a result
– If the function is called with a more complex problem, it divides the
problem into two conceptual pieces—a piece that the function knows
how to process (the base case) and a simpler or smaller version of the
original problem.
• The function invokes (calls) a fresh copy of itself to go to
work on the smaller problem; this invocation is referred
to as a recursive call, or the recursion step.

 2008 Pearson Education, Inc. All rights reserved.


63

9.10 Recursion (Cont.)


• The recursion step executes while the original call to the
function is still open (i.e., it has not finished executing)
• For recursion eventually to terminate, each time the
function calls itself with a simpler version of the original
problem, the sequence of smaller and smaller problems
must converge on the base case
– At that point, the function recognizes the base case, returns a result to
the previous copy of the function, and a sequence of returns ensues up
the line until the original function call eventually returns the final result
to the caller

 2008 Pearson Education, Inc. All rights reserved.


64

While the number to be


processed is greater than 1,
the function calls itself

When the number is 1 or


less (the base case), 1 is
returned, and each
function call can now
return an answer until
each call has been
resolved

Fig. 9.10 | Recursive evaluation of 5!.

 2008 Pearson Education, Inc. All rights reserved.


1 <?xml version = "1.0" encoding = "utf-8"?> 65
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Fig. 9.11 |
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 Factorial
5 <!-- Fig. 9.11: FactorialTest.html --> calculation with
6 <!-- Factorial calculation with a recursive function. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
a recursive
8 <head> function (Part 1
9 <title>Recursive Factorial Function</title>
of 2).
10 <script type = "text/javascript">
11 <!--
12 document.writeln( "<h1>Factorials of 1 to 10</h1>" );
13 document.writeln( "<table>" );
14
15 for ( var i = 0; i <= 10; i++ )
16 document.writeln( "<tr><td>" + i + "!</td><td>" +
17 factorial( i ) + "</td></tr>" ); Calls function factorial
18 with argument i
19 document.writeln( "</table>" );
20 While the base case is not
21 // Recursive definition of function factorial reached, return the
function factorial( number )
22
Base case number * ( number – 1 )!,
23 {
which is number *
24 if ( number <= 1 ) // base case
25 return 1;
factorial
26 else ( number – 1 )
27 return number * factorial( number - 1 ); factorial calls itself
28 } // end function factorial with a new argument and
29 // --> waits until this new value
30 </script> is returned before  2008 Pearson Education,
31 </head><body></body>
returning a value itself Inc. All rights reserved.
32 </html>
66

Fig. 9.11 | Factorial calculation with a recursive function (Part 2 of 2).

 2008 Pearson Education, Inc. All rights reserved.


67

Common Programming Error 9.6

Forgetting to return a value from a recursive


function when one is needed results in a logic
error.

 2008 Pearson Education, Inc. All rights reserved.


68

Common Programming Error 9.7


Omitting the base case and writing the
recursion step incorrectly so that it does not
converge on the base case are both errors that
cause infinite recursion, eventually exhausting
memory. This situation is analogous to the
problem of an infinite loop in an iterative
(nonrecursive) solution.

 2008 Pearson Education, Inc. All rights reserved.


69

Error-Prevention Tip 9.3


Internet Explorer displays an error message
when a script seems to be going into infinite
recursion. Firefox simply terminates the script
after detecting the problem. This allows the
user of the web page to recover from a script
that contains an infinite loop or infinite
recursion.

 2008 Pearson Education, Inc. All rights reserved.


70

9.11 Recursion vs. Iteration

• Both iteration and recursion involve repetition


– Iteration explicitly uses a repetition statement
– Recursion achieves repetition through repeated function
calls
• Iteration and recursion each involve a
termination test
– Iteration terminates when the loop-continuation condition
fails
– Recursion terminates when a base case is recognized

 2008 Pearson Education, Inc. All rights reserved.


71

9.11 Recursion vs. Iteration


• Iteration with counter-controlled repetition and recursion
both gradually approach termination
– Iteration keeps modifying a counter until the counter assumes a value
that makes the loop-continuation condition fail
– Recursion keeps producing simpler versions of the original problem
until the base case is reached
• Recursion repeatedly invokes the mechanism and,
consequently, the overhead of function calls
– expensive in terms of processor time and memory space
• Some problems can be understood or solved more easily
with recursion than with iteration

 2008 Pearson Education, Inc. All rights reserved.


72

Software Engineering Observation 9.6

Any problem that can be solved recursively


can also be solved iteratively (nonrecursively).
A recursive approach is normally chosen in
preference to an iterative approach when the
recursive approach more naturally mirrors
the problem and results in a program that is
easier to understand and debug. Another
reason to choose a recursive solution is that an
iterative solution may not be apparent.

 2008 Pearson Education, Inc. All rights reserved.


73

Performance Tip 9.1

Avoid using recursion in performance-


oriented situations. Recursive calls take time
and consume additional memory.

 2008 Pearson Education, Inc. All rights reserved.


74

Common Programming Error 9.8

Accidentally having a nonrecursive function


call itself, either directly, or indirectly through
another function, can cause infinite recursion.

 2008 Pearson Education, Inc. All rights reserved.

You might also like