SlideShare uma empresa Scribd logo
1 de 60
IPA
1st
Semester, 2007-2008
Internet 1
Ch. 11
JavaScript: Functions
attasr@ipa.edu.sa
09/30/15 © Reem Al-Attas 2
Introduction
Software design
 Break software up into modules
 Easier to maintain and debug
 Divide and conquer
09/30/15 © Reem Al-Attas 3
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
09/30/15 © Reem Al-Attas 4
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
09/30/15 © Reem Al-Attas 5
Program Modules in JavaScript
boss
worker1 worker2 worker3
worker4 worker5
Fig. 10.1 Hierarchical boss-function/worker-function relationship.
09/30/15 © Reem Al-Attas 6
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 );
09/30/15 © Reem Al-Attas 7
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
09/30/15 © Reem Al-Attas 8
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)
09/30/15 © Reem Al-Attas 9
Function Definitions
Returning control
 return statement
 Can return either nothing, or a value
return expression;
 No return statement same as return;
 Not returning a value when expected is an
error
09/30/15 © Reem Al-Attas 10
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
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.2: SquareInt.html -->
6 <!-- Square function -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>A Programmer-Defined square Function</title>
11
12 <script type = "text/javascript">
13 <!--
14 document.writeln(
15 "<h1>Square the numbers from 1 to 10</h1>" );
16
17 // square the numbers from 1 to 10
18 for ( var x = 1; x <= 10; ++x )
19 document.writeln( "The square of " + x + " is " +
20 square( x ) + "<br />" );
21
Calling function square and passing it the value of x.
22 // The following square function's body is executed
23 // only when the function is explicitly called.
24
25 // square function definition
26 function square( y )
27 {
28 return y * y;
29 }
30 // -->
31 </script>
32
33 </head><body></body>
34 </html>
Variable y gets the value of variable x.
The return statement passes the value of y * y back
to the calling function.
09/30/15 © Reem Al-Attas 13
Function Definitions
09/30/15 © Reem Al-Attas 14
Function Definitions
Finding the maximum of 3 numbers
 Prompt for 3 inputs
 Convert to numbers
 Pass to maximum
 Math.max
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.3: maximum.html -->
6 <!-- Maximum function -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Finding the Maximum of Three Values</title>
11
12 <script type = "text/javascript">
13 <!--
14 var input1 =
15 window.prompt( "Enter first number", "0" );
16 var input2 =
17 window.prompt( "Enter second number", "0" );
18 var input3 =
19 window.prompt( "Enter third number", "0" );
20
21 var value1 = parseFloat( input1 );
22 var value2 = parseFloat( input2 );
23 var value3 = parseFloat( input3 );
Prompt for the user to input three integers.
24
25 var maxValue = maximum( value1, value2, value3 );
26
27 document.writeln( "First number: " + value1 +
28 "<br />Second number: " + value2 +
29 "<br />Third number: " + value3 +
30 "<br />Maximum is: " + maxValue );
31
32 // maximum method definition (called from line 25)
33 function maximum( x, y, z )
34 {
35 return Math.max( x, Math.max( y, z ) );
36 }
37 // -->
38 </script>
39
40 </head>
41 <body>
42 <p>Click Refresh (or Reload) to run the script again</p>
43 </body>
44 </html>
Call function maximum and pass it the value of
variables value1, value2 and value3.
Variables x, y and z get the value of variables
value1, value2 and value3, respectively.
Method max returns the larger of the two
integers passed to it.
09/30/15 © Reem Al-Attas 17
Function Definitions
09/30/15 © Reem Al-Attas 18
Function Definitions
09/30/15 © Reem Al-Attas 19
Random-Number Generation
Random-number generation introduces
element of chance
 Math.random
var randomValue = Math.random();
 Floating point value between 0 and 1, but
not including 1.
 Adjust range by scaling and shifting
 Math.floor
 Always round down
Math.floor(1 + Math.random() * 6)
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.4: RandomInt.html -->
6 <!-- Demonstrating the Random method -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Shifted and Scaled Random Integers</title>
11
12 <script type = "text/javascript">
13 <!--
14 var value;
15
16 document.writeln(
17 "<table border = "1" width = "50%">" );
18 document.writeln(
19 "<caption>Random Numbers</caption><tr>" );
20
21 for ( var i = 1; i <= 20; i++ ) {
22 value = Math.floor( 1 + Math.random() * 6 );
23 document.writeln( "<td>" + value + "</td>" );
24
25 // write end and start <tr> tags when
26 // i is a multiple of 5 and not 20
27 if ( i % 5 == 0 && i != 20 )
28 document.writeln( "</tr><tr>" );
29 }
30
31 document.writeln( "</tr></table>" );
32 // -->
33 </script>
34
35 </head>
36 <body>
37 <p>Click Refresh (or Reload) to run the script again</p>
38 </body>
39 </html>
The for loop creates 20
table cells (4 rows x 5
columns).
Each cell is populated
with a random number
generated by method
random.
Method floor rounds the number
generated by method random down.
09/30/15 © Reem Al-Attas 22
Random-Number Generation
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.5: RollDie.html -->
6 <!-- Rolling a Six-Sided Die -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Roll a Six-Sided Die 6000 Times</title>
11
12 <script type = "text/javascript">
13 <!--
14 var frequency1 = 0, frequency2 = 0,
15 frequency3 = 0, frequency4 = 0,
16 frequency5 = 0, frequency6 = 0, face;
17
18 // summarize results
19 for ( var roll = 1; roll <= 6000; ++roll ) {
20 face = Math.floor( 1 + Math.random() * 6 );
21
This expression uses method random to
generate a random number between 1 and 6.
RollDie.html
(2 of 3)
22 switch ( face ) {
23 case 1:
24 ++frequency1;
25 break;
26 case 2:
27 ++frequency2;
28 break;
29 case 3:
30 ++frequency3;
31 break;
32 case 4:
33 ++frequency4;
34 break;
35 case 5:
36 ++frequency5;
37 break;
38 case 6:
39 ++frequency6;
40 break;
41 }
42 }
43
When the controlling expression, face,
matches a case label, the respective
frequency variable is incremented.
RollDie.html
(3 of 3)
44 document.writeln( "<table border = "1"" +
45 "width = "50%">" );
46 document.writeln( "<thead><th>Face</th>" +
47 "<th>Frequency<th></thead>" );
48 document.writeln( "<tbody><tr><td>1</td><td>" +
49 frequency1 + "</td></tr>" );
50 document.writeln( "<tr><td>2</td><td>" + frequency2 +
51 "</td></tr>" );
52 document.writeln( "<tr><td>3</td><td>" + frequency3 +
53 "</td></tr>" );
54 document.writeln( "<tr><td>4</td><td>" + frequency4 +
55 "</td></tr>" );
56 document.writeln( "<tr><td>5</td><td>" + frequency5 +
57 "</td></tr>" );
58 document.writeln( "<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>
The results of rolling the die
600 times are displayed in a
table.
09/30/15 © Reem Al-Attas 26
Random-Number Generation
09/30/15 © Reem Al-Attas 27
Example: Game of Chance
Craps
 Click Roll Dice
 Text fields show rolls, sum and point
 Status bar displays results
09/30/15 © Reem Al-Attas 28
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
09/30/15 © Reem Al-Attas 29
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 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <!-- Fig. 10.6: Craps.html -->
6 <!-- Craps Program -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Program that Simulates the Game of Craps</title>
11
12 <script type = "text/javascript">
13 <!--
14 // variables used to test the state of the game
15 var WON = 0, LOST = 1, CONTINUE_ROLLING = 2;
16
17 // other variables used in program
18 var firstRoll = true, // true if first roll
19 sumOfDice = 0, // sum of the dice
20 myPoint = 0, // point if no win/loss on first roll
21 gameStatus = CONTINUE_ROLLING; // game not over yet
22
23 // process one roll of the dice
24 function play()
25 {
26 if ( firstRoll ) { // first roll of the dice
27 sumOfDice = rollDice();
28
29 switch ( sumOfDice ) {
30 case 7: case 11: // win on first roll
31 gameStatus = WON;
32 // clear point field
33 document.craps.point.value = "";
34 break;
35 case 2: case 3: case 12: // lose on first roll
36 gameStatus = LOST;
37 // clear point field
38 document.craps.point.value = "";
39 break;
40 default: // remember point
41 gameStatus = CONTINUE_ROLLING;
42 myPoint = sumOfDice;
43 document.craps.point.value = myPoint;
44 firstRoll = false;
45 }
46 }
If the value of firstRoll is true, then function
rollDice is called.
If function rollDice returns a value of 7
or 11, the player wins and the break
statement causes program control
proceeds to the first line after the switch
structure.
If function rollDice returns a 2, 3 or 12, the
player loses and the break statement causes
control to proceed to first line after the switch
structure.
47 else {
48 sumOfDice = rollDice();
49
50 if ( sumOfDice == myPoint ) // win by making point
51 gameStatus = WON;
52 else
53 if ( sumOfDice == 7 ) // lose by rolling 7
54 gameStatus = LOST;
55 }
56
57 if ( gameStatus == CONTINUE_ROLLING )
58 window.status = "Roll again";
59 else {
60 if ( gameStatus == WON )
61 window.status = "Player wins. " +
62 "Click Roll Dice to play again.";
63 else
64 window.status = "Player loses. " +
65 "Click Roll Dice to play again.";
66
67 firstRoll = true;
68 }
69 }
70
If the value returned by function rollDice
equals the value of variable myPoint, the player
wins because the point has been reached.
If the values returned by function rollDice
equals 7, the player loses.
window method status displays a
message in the status bar of the browser.
If the value of firstRoll is false,
function rollDice is called to see if the
point has been reached.
Craps.html
(4 of 5)
71 // roll the dice
72 function rollDice()
73 {
74 var die1, die2, workSum;
75
76 die1 = Math.floor( 1 + Math.random() * 6 );
77 die2 = Math.floor( 1 + Math.random() * 6 );
78 workSum = die1 + die2;
79
80 document.craps.firstDie.value = die1;
81 document.craps.secondDie.value = die2;
82 document.craps.sum.value = workSum;
83
84 return workSum;
85 }
86 // -->
87 </script>
88
89 </head>
Function rollDice is called to simulate
the rolling of two dice on the craps table.
Methods random and floor are used to
generate the values for the two dice.
Referencing the names of form elements
in the XHTML document, the values of
the dice are placed in their respective
form fields.
Craps.html
(5 of 5)
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 <td><input name = "secondDie" type = "text" />
99 </td></tr>
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 onclick = "play()" /></td></tr>
108 </table>
109 </form>
110 </body>
111 </html>
09/30/15 © Reem Al-Attas 35
Example: Game of Chance
A text XHTML GUI component
A button XHTML GUI component
Browser’s status bar
09/30/15 © Reem Al-Attas 36
Example: Game of Chance
09/30/15 © Reem Al-Attas 37
Example: Game of Chance
09/30/15 © Reem Al-Attas 38
Another Example: Random Image
Generator
Randomly selecting an image
 Images have integer names (i.e., 1.gif,
2.gif, …, 7.gif)
 Generate random number in proper range
 Update src property
RandomPicture.html
(1 of 1)
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- Fig. 10.7: RandomPicture.html -->
6 <!-- Randomly displays one of 7 images -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Random Image Generator</title>
11
12 <script type = "text/javascript">
13 <!--
14 document.write ( "<img src = "" +
15 Math.floor( 1 + Math.random() * 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>
Inserting a random number into the image’s src
property with document.write and Math.random
09/30/15 © Reem Al-Attas 40
Another Example: Random Image
Generator
09/30/15 © Reem Al-Attas 41
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
09/30/15 © Reem Al-Attas 42
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 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.8: scoping.html -->
6 <!-- Local and Global Variables -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>A Scoping Example</title>
11
12 <script type = "text/javascript">
13 <!--
14 var x = 1; // global variable
15
16 function start()
17 {
18 var x = 5; // variable local to function start
19
20 document.writeln( "local x in start is " + x );
21
22 functionA(); // functionA has local x
23 functionB(); // functionB uses global variable x
24 functionA(); // functionA reinitializes local x
25 functionB(); // global variable x retains its value
To begin the program, variable x is initialized to 1.
Function start changes the value of x to 5.
Scoping.html
(2 of 3)
26
27 document.writeln(
28 "<p>local x in start is " + x + "</p>" );
29 }
30
31 function functionA()
32 {
33 var x = 25; // initialized each time
34 // functionA is called
35
36 document.writeln( "<p>local x in functionA is " +
37 x + " after entering functionA" );
38 ++x;
39 document.writeln( "<br />local x in functionA is " +
40 x + " before exiting functionA" + "</p>" );
41 }
42
Function functionA changes the value of x to 25.
The value of x is incremented.
Scoping.html
(3 of 3)
43 function functionB()
44 {
45 document.writeln( "<p>global variable x is " + x +
46 " on entering functionB" );
47 x *= 10;
48 document.writeln( "<br />global variable x is " +
49 x + " on exiting functionB" + "</p>" );
50 }
51 // -->
52 </script>
53
54 </head>
55 <body onload = "start()"></body>
56 </html>
Function functionB multiplies the value of x by 10.
09/30/15 © Reem Al-Attas 46
Scope Rules
09/30/15 © Reem Al-Attas 47
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
09/30/15 © Reem Al-Attas 48
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
09/30/15 © Reem Al-Attas 49
Recursion
5!
5 * 4!
4 * 3!
3 * 2!
2 * 1!
1
5!
5 * 4!
4 * 3!
3 * 2!
2 * 1!
1
(a) Procession of recursive calls. (b) Values returned from each recursive call.
5! = 5 * 24 = 120 is returned
4! = 4 * 6 = 24 is returned
2! = 2 * 1 = 2 is returned
3! = 3 * 2 = 6 is returned
1 returned
Fig. 10.10 Recursive evaluation of 5!.
Final value = 120
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.11: FactorialTest.html -->
6 <!-- Recursive factorial example -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Recursive Factorial Function</title>
11
12 <script language = "javascript">
13 document.writeln( "<h1>Factorials of 1 to 10</h1>" );
14 document.writeln(
15 "<table border = '1' width = '100%'>" );
16
17 for ( var i = 0; i <= 10; i++ )
18 document.writeln( "<tr><td>" + i + "!</td><td>" +
19 factorial( i ) + "</td></tr>" );
20
21 document.writeln( "</table>" );
22
Calling function factorial and passing
it the value of i.
23 // Recursive definition of function factorial
24 function factorial( number )
25 {
26 if ( number <= 1 ) // base case
27 return 1;
28 else
29 return number * factorial( number - 1 );
30 }
31 </script>
32 </head><body></body>
33 </html>
Variable number gets the value of variable i.
Call to function factorial and passing it 1
less than the current value of number .
09/30/15 © Reem Al-Attas 52
Recursion
09/30/15 © Reem Al-Attas 53
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
<INPUT TYPE = “button” VALUE = “buttonLabel”
ONCLICK = “javaScriptFunctionCall”>
 Function called in ONCLICK element is executed when
event is executed
 Function called in GUI will execute using FORM elements
as its parameters
09/30/15 © Reem Al-Attas 54
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: FibonacciTest.html -->
4
5 <HEAD>
6 <TITLE>Recursive Fibonacci Function</TITLE>
7
8 <SCRIPT LANGUAGE = "JavaScript">
9 // Event handler for button HTML component in myForm
10 function getFibonacciValue()
11 {
12 var value = parseInt( document.myForm.number.value );
13 window.status =
14 "Calculating Fibonacci number for " + value;
15 document.myForm.result.value = fibonacci( value );
16 window.status = "Done calculating Fibonacci number";
17 }
18
19 // Recursive definition of function fibonacci
20 function fibonacci( n )
21 {
22 if ( n == 0 || n == 1 ) // base case
23 return n;
24 else
25 return fibonacci( n - 1 ) + fibonacci( n - 2 );
26 }
27 </SCRIPT>
28
29 </HEAD>
30
34 <TR><TD>Enter an integer</TD>
35 <TD><INPUT NAME = "number" TYPE = "text"></TD>
36 <TD><INPUT TYPE = "button" VALUE = "Calculate"
37 ONCLICK = "getFibonacciValue()"</TR>
38 <TR><TD>Fibonacci value</TD>
39 <TD><INPUT NAME = "result" TYPE = "text"></TD></TR>
40 </TABLE>
41</FORM></BODY>
42</HTML>
31<BODY>
32<FORM NAME = "myForm">
33 <TABLE BORDER = "1">
09/30/15 © Reem Al-Attas 57
Script Outputs:
09/30/15 © Reem Al-Attas 58
Example of Using Recursion: The
Fibonacci Series
Set of Recursive Calls to Function fibonacci
return 1 return 0
f( 1 )return f( 0 )+ return 1
f( 2 )return f( 1 )+
f( 3 )
09/30/15 © Reem Al-Attas 59
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
with naturally recursive solution
09/30/15 © Reem Al-Attas 60
Assignment 8
 1) Exercise # 10.22:
 A & B
 C (Bonus)
Due Date for A # 8:
 Next Monday before
your lecture.

Mais conteúdo relacionado

Mais procurados

Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
Client side scripting using Javascript
Client side scripting using JavascriptClient side scripting using Javascript
Client side scripting using Javascript
Bansari Shah
 

Mais procurados (20)

javascript objects
javascript objectsjavascript objects
javascript objects
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Javascript validating form
Javascript validating formJavascript validating form
Javascript validating form
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy steps
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Client side scripting using Javascript
Client side scripting using JavascriptClient side scripting using Javascript
Client side scripting using Javascript
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Js ppt
Js pptJs ppt
Js ppt
 
Javascript
JavascriptJavascript
Javascript
 
Web Development with HTML5, CSS3 & JavaScript
Web Development with HTML5, CSS3 & JavaScriptWeb Development with HTML5, CSS3 & JavaScript
Web Development with HTML5, CSS3 & JavaScript
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 

Destaque

Destaque (8)

JavaScript Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional Statements
 
Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]
 
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
 
She Looks Just Like Me 2017
She Looks Just Like Me 2017She Looks Just Like Me 2017
She Looks Just Like Me 2017
 
Evolutionary Algorithms
Evolutionary AlgorithmsEvolutionary Algorithms
Evolutionary Algorithms
 
High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010
 
JavaScript Prototype and Module Pattern
JavaScript Prototype and Module PatternJavaScript Prototype and Module Pattern
JavaScript Prototype and Module Pattern
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 

Semelhante a JavaScript Functions

Distributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation ProjectDistributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation Project
Assignmentpedia
 
Distributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation ProjectDistributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation Project
Assignmentpedia
 

Semelhante a JavaScript Functions (20)

JavaScript Control Statements II
JavaScript Control Statements IIJavaScript Control Statements II
JavaScript Control Statements II
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
 
Dynamic HTML Event Model
Dynamic HTML Event ModelDynamic HTML Event Model
Dynamic HTML Event Model
 
JavaScript Control Statements I
JavaScript Control Statements IJavaScript Control Statements I
JavaScript Control Statements I
 
Synapse india basic php development part 2
Synapse india basic php development part 2Synapse india basic php development part 2
Synapse india basic php development part 2
 
Java script
Java scriptJava script
Java script
 
Synapse india basic php development part 1
Synapse india basic php development part 1Synapse india basic php development part 1
Synapse india basic php development part 1
 
JavaScript
JavaScriptJavaScript
JavaScript
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35
 
Distributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation ProjectDistributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation Project
 
Distributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation ProjectDistributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation Project
 
WMQ Toolbox: 20 Scripts, One-liners, & Utilities for UNIX & Windows
WMQ Toolbox: 20 Scripts, One-liners, & Utilities for UNIX & Windows WMQ Toolbox: 20 Scripts, One-liners, & Utilities for UNIX & Windows
WMQ Toolbox: 20 Scripts, One-liners, & Utilities for UNIX & Windows
 
Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26
 
PHP Scripting
PHP ScriptingPHP Scripting
PHP Scripting
 
Pl sql using_xml
Pl sql using_xmlPl sql using_xml
Pl sql using_xml
 
JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptx
 
Synapse india dotnet development web approch
Synapse india dotnet development web approchSynapse india dotnet development web approch
Synapse india dotnet development web approch
 
Synapse india reviews sharing chapter 23 – asp.net-part2
Synapse india reviews sharing  chapter 23 – asp.net-part2Synapse india reviews sharing  chapter 23 – asp.net-part2
Synapse india reviews sharing chapter 23 – asp.net-part2
 
New Component Patterns in Ember.js
New Component Patterns in Ember.jsNew Component Patterns in Ember.js
New Component Patterns in Ember.js
 
Javascript.ppt
Javascript.pptJavascript.ppt
Javascript.ppt
 

Mais de Reem Alattas

Mais de Reem Alattas (20)

Rumble Lights Pitch Deck
Rumble Lights Pitch DeckRumble Lights Pitch Deck
Rumble Lights Pitch Deck
 
NASA Datanauts Water Cooler Chat: Autonomous Design of Modular Robots
NASA Datanauts Water Cooler Chat: Autonomous Design of Modular RobotsNASA Datanauts Water Cooler Chat: Autonomous Design of Modular Robots
NASA Datanauts Water Cooler Chat: Autonomous Design of Modular Robots
 
She looks just like me 2017
She looks just like me 2017She looks just like me 2017
She looks just like me 2017
 
Nasa Datanauts Water Cooler Chat: Robotics for Space Exploration
Nasa Datanauts Water Cooler Chat: Robotics for Space ExplorationNasa Datanauts Water Cooler Chat: Robotics for Space Exploration
Nasa Datanauts Water Cooler Chat: Robotics for Space Exploration
 
Nasa Datanauts Water Cooler Chat: Evolutionary Robots for Space Exploration
Nasa Datanauts Water Cooler Chat: Evolutionary Robots for Space ExplorationNasa Datanauts Water Cooler Chat: Evolutionary Robots for Space Exploration
Nasa Datanauts Water Cooler Chat: Evolutionary Robots for Space Exploration
 
Tran helmet pitch
Tran helmet pitchTran helmet pitch
Tran helmet pitch
 
Evolutionary Robotics
Evolutionary RoboticsEvolutionary Robotics
Evolutionary Robotics
 
Create a Need
Create a NeedCreate a Need
Create a Need
 
Enhancing input on and above the interactive surface
Enhancing input on and above the interactive surfaceEnhancing input on and above the interactive surface
Enhancing input on and above the interactive surface
 
Skinput: Appropriating the Body as an Input Surface
Skinput: Appropriating the Body as an Input SurfaceSkinput: Appropriating the Body as an Input Surface
Skinput: Appropriating the Body as an Input Surface
 
XML - EXtensible Markup Language
XML - EXtensible Markup LanguageXML - EXtensible Markup Language
XML - EXtensible Markup Language
 
DHTML - Dynamic HTML
DHTML - Dynamic HTMLDHTML - Dynamic HTML
DHTML - Dynamic HTML
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
Linear Search & Binary Search
Linear Search & Binary SearchLinear Search & Binary Search
Linear Search & Binary Search
 
Cascading Style Sheet - CSS
Cascading Style Sheet - CSSCascading Style Sheet - CSS
Cascading Style Sheet - CSS
 
HTML tables- rowspan n colspan
HTML tables- rowspan n colspanHTML tables- rowspan n colspan
HTML tables- rowspan n colspan
 
Introduction to HTML
Introduction to HTMLIntroduction to HTML
Introduction to HTML
 
Ethical and Legal Issues and the Case Study
Ethical and Legal Issues and the Case StudyEthical and Legal Issues and the Case Study
Ethical and Legal Issues and the Case Study
 
Network Security
Network SecurityNetwork Security
Network Security
 
Human Factors and Professional Issues
Human Factors and Professional IssuesHuman Factors and Professional Issues
Human Factors and Professional Issues
 

Último

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Último (20)

HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 

JavaScript Functions

  • 1. IPA 1st Semester, 2007-2008 Internet 1 Ch. 11 JavaScript: Functions attasr@ipa.edu.sa
  • 2. 09/30/15 © Reem Al-Attas 2 Introduction Software design  Break software up into modules  Easier to maintain and debug  Divide and conquer
  • 3. 09/30/15 © Reem Al-Attas 3 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
  • 4. 09/30/15 © Reem Al-Attas 4 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
  • 5. 09/30/15 © Reem Al-Attas 5 Program Modules in JavaScript boss worker1 worker2 worker3 worker4 worker5 Fig. 10.1 Hierarchical boss-function/worker-function relationship.
  • 6. 09/30/15 © Reem Al-Attas 6 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 );
  • 7. 09/30/15 © Reem Al-Attas 7 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
  • 8. 09/30/15 © Reem Al-Attas 8 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)
  • 9. 09/30/15 © Reem Al-Attas 9 Function Definitions Returning control  return statement  Can return either nothing, or a value return expression;  No return statement same as return;  Not returning a value when expected is an error
  • 10. 09/30/15 © Reem Al-Attas 10 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
  • 11. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.2: SquareInt.html --> 6 <!-- Square function --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>A Programmer-Defined square Function</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 document.writeln( 15 "<h1>Square the numbers from 1 to 10</h1>" ); 16 17 // square the numbers from 1 to 10 18 for ( var x = 1; x <= 10; ++x ) 19 document.writeln( "The square of " + x + " is " + 20 square( x ) + "<br />" ); 21 Calling function square and passing it the value of x.
  • 12. 22 // The following square function's body is executed 23 // only when the function is explicitly called. 24 25 // square function definition 26 function square( y ) 27 { 28 return y * y; 29 } 30 // --> 31 </script> 32 33 </head><body></body> 34 </html> Variable y gets the value of variable x. The return statement passes the value of y * y back to the calling function.
  • 13. 09/30/15 © Reem Al-Attas 13 Function Definitions
  • 14. 09/30/15 © Reem Al-Attas 14 Function Definitions Finding the maximum of 3 numbers  Prompt for 3 inputs  Convert to numbers  Pass to maximum  Math.max
  • 15. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.3: maximum.html --> 6 <!-- Maximum function --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Finding the Maximum of Three Values</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var input1 = 15 window.prompt( "Enter first number", "0" ); 16 var input2 = 17 window.prompt( "Enter second number", "0" ); 18 var input3 = 19 window.prompt( "Enter third number", "0" ); 20 21 var value1 = parseFloat( input1 ); 22 var value2 = parseFloat( input2 ); 23 var value3 = parseFloat( input3 ); Prompt for the user to input three integers.
  • 16. 24 25 var maxValue = maximum( value1, value2, value3 ); 26 27 document.writeln( "First number: " + value1 + 28 "<br />Second number: " + value2 + 29 "<br />Third number: " + value3 + 30 "<br />Maximum is: " + maxValue ); 31 32 // maximum method definition (called from line 25) 33 function maximum( x, y, z ) 34 { 35 return Math.max( x, Math.max( y, z ) ); 36 } 37 // --> 38 </script> 39 40 </head> 41 <body> 42 <p>Click Refresh (or Reload) to run the script again</p> 43 </body> 44 </html> Call function maximum and pass it the value of variables value1, value2 and value3. Variables x, y and z get the value of variables value1, value2 and value3, respectively. Method max returns the larger of the two integers passed to it.
  • 17. 09/30/15 © Reem Al-Attas 17 Function Definitions
  • 18. 09/30/15 © Reem Al-Attas 18 Function Definitions
  • 19. 09/30/15 © Reem Al-Attas 19 Random-Number Generation Random-number generation introduces element of chance  Math.random var randomValue = Math.random();  Floating point value between 0 and 1, but not including 1.  Adjust range by scaling and shifting  Math.floor  Always round down Math.floor(1 + Math.random() * 6)
  • 20. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.4: RandomInt.html --> 6 <!-- Demonstrating the Random method --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Shifted and Scaled Random Integers</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var value; 15 16 document.writeln( 17 "<table border = "1" width = "50%">" ); 18 document.writeln( 19 "<caption>Random Numbers</caption><tr>" ); 20
  • 21. 21 for ( var i = 1; i <= 20; i++ ) { 22 value = Math.floor( 1 + Math.random() * 6 ); 23 document.writeln( "<td>" + value + "</td>" ); 24 25 // write end and start <tr> tags when 26 // i is a multiple of 5 and not 20 27 if ( i % 5 == 0 && i != 20 ) 28 document.writeln( "</tr><tr>" ); 29 } 30 31 document.writeln( "</tr></table>" ); 32 // --> 33 </script> 34 35 </head> 36 <body> 37 <p>Click Refresh (or Reload) to run the script again</p> 38 </body> 39 </html> The for loop creates 20 table cells (4 rows x 5 columns). Each cell is populated with a random number generated by method random. Method floor rounds the number generated by method random down.
  • 22. 09/30/15 © Reem Al-Attas 22 Random-Number Generation
  • 23. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.5: RollDie.html --> 6 <!-- Rolling a Six-Sided Die --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Roll a Six-Sided Die 6000 Times</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var frequency1 = 0, frequency2 = 0, 15 frequency3 = 0, frequency4 = 0, 16 frequency5 = 0, frequency6 = 0, face; 17 18 // summarize results 19 for ( var roll = 1; roll <= 6000; ++roll ) { 20 face = Math.floor( 1 + Math.random() * 6 ); 21 This expression uses method random to generate a random number between 1 and 6.
  • 24. RollDie.html (2 of 3) 22 switch ( face ) { 23 case 1: 24 ++frequency1; 25 break; 26 case 2: 27 ++frequency2; 28 break; 29 case 3: 30 ++frequency3; 31 break; 32 case 4: 33 ++frequency4; 34 break; 35 case 5: 36 ++frequency5; 37 break; 38 case 6: 39 ++frequency6; 40 break; 41 } 42 } 43 When the controlling expression, face, matches a case label, the respective frequency variable is incremented.
  • 25. RollDie.html (3 of 3) 44 document.writeln( "<table border = "1"" + 45 "width = "50%">" ); 46 document.writeln( "<thead><th>Face</th>" + 47 "<th>Frequency<th></thead>" ); 48 document.writeln( "<tbody><tr><td>1</td><td>" + 49 frequency1 + "</td></tr>" ); 50 document.writeln( "<tr><td>2</td><td>" + frequency2 + 51 "</td></tr>" ); 52 document.writeln( "<tr><td>3</td><td>" + frequency3 + 53 "</td></tr>" ); 54 document.writeln( "<tr><td>4</td><td>" + frequency4 + 55 "</td></tr>" ); 56 document.writeln( "<tr><td>5</td><td>" + frequency5 + 57 "</td></tr>" ); 58 document.writeln( "<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> The results of rolling the die 600 times are displayed in a table.
  • 26. 09/30/15 © Reem Al-Attas 26 Random-Number Generation
  • 27. 09/30/15 © Reem Al-Attas 27 Example: Game of Chance Craps  Click Roll Dice  Text fields show rolls, sum and point  Status bar displays results
  • 28. 09/30/15 © Reem Al-Attas 28 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
  • 29. 09/30/15 © Reem Al-Attas 29 Example: Game of Chance Changing properties  Access with dot (.) notation  value property of text fields  status property of window
  • 30. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 <!-- Fig. 10.6: Craps.html --> 6 <!-- Craps Program --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Program that Simulates the Game of Craps</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 // variables used to test the state of the game 15 var WON = 0, LOST = 1, CONTINUE_ROLLING = 2; 16 17 // other variables used in program 18 var firstRoll = true, // true if first roll 19 sumOfDice = 0, // sum of the dice 20 myPoint = 0, // point if no win/loss on first roll 21 gameStatus = CONTINUE_ROLLING; // game not over yet 22
  • 31. 23 // process one roll of the dice 24 function play() 25 { 26 if ( firstRoll ) { // first roll of the dice 27 sumOfDice = rollDice(); 28 29 switch ( sumOfDice ) { 30 case 7: case 11: // win on first roll 31 gameStatus = WON; 32 // clear point field 33 document.craps.point.value = ""; 34 break; 35 case 2: case 3: case 12: // lose on first roll 36 gameStatus = LOST; 37 // clear point field 38 document.craps.point.value = ""; 39 break; 40 default: // remember point 41 gameStatus = CONTINUE_ROLLING; 42 myPoint = sumOfDice; 43 document.craps.point.value = myPoint; 44 firstRoll = false; 45 } 46 } If the value of firstRoll is true, then function rollDice is called. If function rollDice returns a value of 7 or 11, the player wins and the break statement causes program control proceeds to the first line after the switch structure. If function rollDice returns a 2, 3 or 12, the player loses and the break statement causes control to proceed to first line after the switch structure.
  • 32. 47 else { 48 sumOfDice = rollDice(); 49 50 if ( sumOfDice == myPoint ) // win by making point 51 gameStatus = WON; 52 else 53 if ( sumOfDice == 7 ) // lose by rolling 7 54 gameStatus = LOST; 55 } 56 57 if ( gameStatus == CONTINUE_ROLLING ) 58 window.status = "Roll again"; 59 else { 60 if ( gameStatus == WON ) 61 window.status = "Player wins. " + 62 "Click Roll Dice to play again."; 63 else 64 window.status = "Player loses. " + 65 "Click Roll Dice to play again."; 66 67 firstRoll = true; 68 } 69 } 70 If the value returned by function rollDice equals the value of variable myPoint, the player wins because the point has been reached. If the values returned by function rollDice equals 7, the player loses. window method status displays a message in the status bar of the browser. If the value of firstRoll is false, function rollDice is called to see if the point has been reached.
  • 33. Craps.html (4 of 5) 71 // roll the dice 72 function rollDice() 73 { 74 var die1, die2, workSum; 75 76 die1 = Math.floor( 1 + Math.random() * 6 ); 77 die2 = Math.floor( 1 + Math.random() * 6 ); 78 workSum = die1 + die2; 79 80 document.craps.firstDie.value = die1; 81 document.craps.secondDie.value = die2; 82 document.craps.sum.value = workSum; 83 84 return workSum; 85 } 86 // --> 87 </script> 88 89 </head> Function rollDice is called to simulate the rolling of two dice on the craps table. Methods random and floor are used to generate the values for the two dice. Referencing the names of form elements in the XHTML document, the values of the dice are placed in their respective form fields.
  • 34. Craps.html (5 of 5) 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 <td><input name = "secondDie" type = "text" /> 99 </td></tr> 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 onclick = "play()" /></td></tr> 108 </table> 109 </form> 110 </body> 111 </html>
  • 35. 09/30/15 © Reem Al-Attas 35 Example: Game of Chance A text XHTML GUI component A button XHTML GUI component Browser’s status bar
  • 36. 09/30/15 © Reem Al-Attas 36 Example: Game of Chance
  • 37. 09/30/15 © Reem Al-Attas 37 Example: Game of Chance
  • 38. 09/30/15 © Reem Al-Attas 38 Another Example: Random Image Generator Randomly selecting an image  Images have integer names (i.e., 1.gif, 2.gif, …, 7.gif)  Generate random number in proper range  Update src property
  • 39. RandomPicture.html (1 of 1) 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 10.7: RandomPicture.html --> 6 <!-- Randomly displays one of 7 images --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Random Image Generator</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 document.write ( "<img src = "" + 15 Math.floor( 1 + Math.random() * 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> Inserting a random number into the image’s src property with document.write and Math.random
  • 40. 09/30/15 © Reem Al-Attas 40 Another Example: Random Image Generator
  • 41. 09/30/15 © Reem Al-Attas 41 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
  • 42. 09/30/15 © Reem Al-Attas 42 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
  • 43. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.8: scoping.html --> 6 <!-- Local and Global Variables --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>A Scoping Example</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var x = 1; // global variable 15 16 function start() 17 { 18 var x = 5; // variable local to function start 19 20 document.writeln( "local x in start is " + x ); 21 22 functionA(); // functionA has local x 23 functionB(); // functionB uses global variable x 24 functionA(); // functionA reinitializes local x 25 functionB(); // global variable x retains its value To begin the program, variable x is initialized to 1. Function start changes the value of x to 5.
  • 44. Scoping.html (2 of 3) 26 27 document.writeln( 28 "<p>local x in start is " + x + "</p>" ); 29 } 30 31 function functionA() 32 { 33 var x = 25; // initialized each time 34 // functionA is called 35 36 document.writeln( "<p>local x in functionA is " + 37 x + " after entering functionA" ); 38 ++x; 39 document.writeln( "<br />local x in functionA is " + 40 x + " before exiting functionA" + "</p>" ); 41 } 42 Function functionA changes the value of x to 25. The value of x is incremented.
  • 45. Scoping.html (3 of 3) 43 function functionB() 44 { 45 document.writeln( "<p>global variable x is " + x + 46 " on entering functionB" ); 47 x *= 10; 48 document.writeln( "<br />global variable x is " + 49 x + " on exiting functionB" + "</p>" ); 50 } 51 // --> 52 </script> 53 54 </head> 55 <body onload = "start()"></body> 56 </html> Function functionB multiplies the value of x by 10.
  • 46. 09/30/15 © Reem Al-Attas 46 Scope Rules
  • 47. 09/30/15 © Reem Al-Attas 47 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
  • 48. 09/30/15 © Reem Al-Attas 48 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
  • 49. 09/30/15 © Reem Al-Attas 49 Recursion 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 (a) Procession of recursive calls. (b) Values returned from each recursive call. 5! = 5 * 24 = 120 is returned 4! = 4 * 6 = 24 is returned 2! = 2 * 1 = 2 is returned 3! = 3 * 2 = 6 is returned 1 returned Fig. 10.10 Recursive evaluation of 5!. Final value = 120
  • 50. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.11: FactorialTest.html --> 6 <!-- Recursive factorial example --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Recursive Factorial Function</title> 11 12 <script language = "javascript"> 13 document.writeln( "<h1>Factorials of 1 to 10</h1>" ); 14 document.writeln( 15 "<table border = '1' width = '100%'>" ); 16 17 for ( var i = 0; i <= 10; i++ ) 18 document.writeln( "<tr><td>" + i + "!</td><td>" + 19 factorial( i ) + "</td></tr>" ); 20 21 document.writeln( "</table>" ); 22 Calling function factorial and passing it the value of i.
  • 51. 23 // Recursive definition of function factorial 24 function factorial( number ) 25 { 26 if ( number <= 1 ) // base case 27 return 1; 28 else 29 return number * factorial( number - 1 ); 30 } 31 </script> 32 </head><body></body> 33 </html> Variable number gets the value of variable i. Call to function factorial and passing it 1 less than the current value of number .
  • 52. 09/30/15 © Reem Al-Attas 52 Recursion
  • 53. 09/30/15 © Reem Al-Attas 53 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 <INPUT TYPE = “button” VALUE = “buttonLabel” ONCLICK = “javaScriptFunctionCall”>  Function called in ONCLICK element is executed when event is executed  Function called in GUI will execute using FORM elements as its parameters
  • 54. 09/30/15 © Reem Al-Attas 54 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
  • 55. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <!-- Fig. 11.10: FibonacciTest.html --> 4 5 <HEAD> 6 <TITLE>Recursive Fibonacci Function</TITLE> 7 8 <SCRIPT LANGUAGE = "JavaScript"> 9 // Event handler for button HTML component in myForm 10 function getFibonacciValue() 11 { 12 var value = parseInt( document.myForm.number.value ); 13 window.status = 14 "Calculating Fibonacci number for " + value; 15 document.myForm.result.value = fibonacci( value ); 16 window.status = "Done calculating Fibonacci number"; 17 } 18 19 // Recursive definition of function fibonacci 20 function fibonacci( n ) 21 { 22 if ( n == 0 || n == 1 ) // base case 23 return n; 24 else 25 return fibonacci( n - 1 ) + fibonacci( n - 2 ); 26 } 27 </SCRIPT> 28 29 </HEAD> 30
  • 56. 34 <TR><TD>Enter an integer</TD> 35 <TD><INPUT NAME = "number" TYPE = "text"></TD> 36 <TD><INPUT TYPE = "button" VALUE = "Calculate" 37 ONCLICK = "getFibonacciValue()"</TR> 38 <TR><TD>Fibonacci value</TD> 39 <TD><INPUT NAME = "result" TYPE = "text"></TD></TR> 40 </TABLE> 41</FORM></BODY> 42</HTML> 31<BODY> 32<FORM NAME = "myForm"> 33 <TABLE BORDER = "1">
  • 57. 09/30/15 © Reem Al-Attas 57 Script Outputs:
  • 58. 09/30/15 © Reem Al-Attas 58 Example of Using Recursion: The Fibonacci Series Set of Recursive Calls to Function fibonacci return 1 return 0 f( 1 )return f( 0 )+ return 1 f( 2 )return f( 1 )+ f( 3 )
  • 59. 09/30/15 © Reem Al-Attas 59 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 with naturally recursive solution
  • 60. 09/30/15 © Reem Al-Attas 60 Assignment 8  1) Exercise # 10.22:  A & B  C (Bonus) Due Date for A # 8:  Next Monday before your lecture.