0% found this document useful (0 votes)
42 views27 pages

Javascript: Functions: Outline

This document discusses JavaScript functions and how they can be used to modularize programs. It explains that functions allow breaking programs into smaller, reusable modules called functions. Functions can receive input through arguments and return outputs. The document provides examples of defining functions to calculate the square of a number and find the maximum of three numbers by prompting the user for input and passing the values to functions. It demonstrates how functions allow breaking problems down into smaller pieces and passing data between functions through arguments and return values.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views27 pages

Javascript: Functions: Outline

This document discusses JavaScript functions and how they can be used to modularize programs. It explains that functions allow breaking programs into smaller, reusable modules called functions. Functions can receive input through arguments and return outputs. The document provides examples of defining functions to calculate the square of a number and find the maximum of three numbers by prompting the user for input and passing the values to functions. It demonstrates how functions allow breaking problems down into smaller pieces and passing data between functions through arguments and return values.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 27

1

JavaScript: Functions
Outline
Introduction
Program Modules in JavaScript
Programmer-Defined Functions
Function Definitions
Random-Number Generation
2

Objectives

• In this tutorial, you will learn:


– To understand how to construct programs modularly from
small pieces called functions.
– To be able to create new functions.
– To understand the mechanisms used to pass information
between functions.
– To introduce simulation techniques that use random-number
generation.
– To understand how the visibility of identifiers is limited to
specific regions of programs.
3

10.1 Introduction

• Software design
– Break software up into modules
• Easier to maintain and debug
– Divide and conquer
4

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
5

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
6

Program Modules in JavaScript

boss

worker1 worker2 worker3

worker4 worker5

Fig. 10.1 Hierarchical boss-function/worker-function relationship.


7

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 );
8

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
9

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)
10

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
11

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"?> 12
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.2: SquareInt.html -->
SquareInt.html
6 <!-- Square function -->
(1 of 2)
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 Calling
"<h1>Square the numbers from 1function
to 10</h1>" );
square and passing it the value of x.
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

 2004 Prentice Hall, Inc.


All rights reserved.
22 // The following square function's body is executed
13
// only when the functionVariable y gets called.
the value of variable x.
23 is explicitly
Outline
24
25 // square function definition
26 function square( y ) SquareInt.html
27 { (2 of 2)
28 return y * y;
29 }
30 // -->
The return statement passes the value of y * y back
31 </script>
to the calling function.
32
33 </head><body></body>
34 </html>

 2004 Prentice Hall, Inc.


All rights reserved.
14

Function Definitions
Fig. 10.2 Using programmer-defined function square.
15

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"?>
16
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.3: maximum.html --> Maximum.html
6 <!-- Maximum function --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Finding the Maximum of Three Values</title>
11 Prompt for the user to input three integers.
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 );

 2004 Prentice Hall, Inc.


All rights reserved.
24
17
25 var maxValue = maximum( value1, value2, value3 );
Outline
26
27 document.writeln( "First number: " + value1 +
Call function maximum and pass it the value of
28 "<br />Second number: " + value2 +
variables value1, value2 and value3.Maximum.html
29 "<br />Third number: " + value3 + (2 of 2)
30 "<br />Maximum is: " + maxValue );
Method max returns the larger of the two
31
integers passed to it.
32 // maximum method definition (called from line 25)
33 function maximum( x, y, z )
34 {
35 return Math.max( x, Math.max( Variables
y, z ) ); x,
y and z get the value of variables
36 } value1, value2 and value3, respectively.
37 // -->
38 </script>
39
40 </head>
41 <body>
42 <p>Click Refresh (or Reload) to run the script again</p>
43 </body>
44 </html>

 2004 Prentice Hall, Inc.


All rights reserved.
18

Function Definitions
Fig. 10.3 Programmer-defined maximum function (1 of 2).
19

Function Definitions
Fig. 10.3 Programmer-defined maximum function (2 of 2).
20

Random-Number Generation

• Random-number generation introduces element of


chance
– Math.random
var randomValue = Math.random();
– Floating point value between 0 and 1
– Adjust range by scaling and shifting
– Math.floor
• Always round down
Math.floor( 1 + Math.random() * 6 )
1 <?xml version = "1.0"?>
21
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.4: RandomInt.html --> RandomInt.html
6 <!-- Demonstrating the Random method --> (1 of 2)
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

 2004 Prentice Hall, Inc.


All rights reserved.
21 for ( var i = 1; i <= 20; i++ ) {
22
22 value = Math.floor( 1 + Math.random() * 6 ); Method floor rounds the number
Outline
23 document.writeln( "<td>" + value + "</td>" ); generated by method random down.
24
25 // write end and start <tr> tags when RandomInt.html
26 // i is a multiple of 5 and not 20 (2 of 2)
Each cell is populated
27 The for loop if creates
( i % 5 20
== 0 && i != 20 ) with a random number
28 table cells (4 rows x5
document.writeln( "</tr><tr>" ); generated by method
29 columns).} random.
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>

 2004 Prentice Hall, Inc.


All rights reserved.
23

Random-Number Generation
Fig. 10.4 Random integers, shifting and scaling.
1 <?xml version = "1.0"?>
24
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.5: RollDie.html --> RollDie.html
6 <!-- Rolling a Six-Sided Die --> (1 of 3)
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 <!--
This expression uses method random to
14 var frequency1 = 0, frequency2 =
generate
0,
a random number between 1 and 6.
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

 2004 Prentice Hall, Inc.


All rights reserved.
22 switch ( face ) {
25
23 case 1:
Outline
24 ++frequency1;
25 break;
When the controlling expression, face,
26 case 2:
matches a case label, the respective RollDie.html
27 ++frequency2;
frequency variable is incremented. (2 of 3)
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

 2004 Prentice Hall, Inc.


All rights reserved.
44 document.writeln( "<table border = \"1\"" +
26
45 "width = \"50%\">" );
Outline
The results of rolling the die
46 document.writeln( "<thead><th>Face</th>" +
47 "<th>Frequency<th></thead>" );
600 times are displayed in a
48 document.writeln( "<tbody><tr><td>1</td><td>" +
table. RollDie.html
49 frequency1 + "</td></tr>" ); (3 of 3)
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>

 2004 Prentice Hall, Inc.


All rights reserved.
27

Random-Number Generation
Fig. 10.5 Rolling a six-sided die 6000 times.

You might also like