Javascript: Functions: Outline
Javascript: Functions: Outline
Javascript: Functions: Outline
JavaScript: Functions
Outline
Introduction
Program Modules in JavaScript
Programmer-Defined Functions
Function Definitions
Random-Number Generation
2
Objectives
10.1 Introduction
• Software design
– Break software up into modules
• Easier to maintain and debug
– Divide and conquer
4
• 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
• 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
boss
worker4 worker5
• Function calls
– Name
– Left parenthesis
– Arguments separated by commas
• Constants, variables or expressions
– Right parenthesis
– Examples:
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
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
Function Definitions
Fig. 10.2 Using programmer-defined function square.
15
Function Definitions
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
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
Random-Number Generation
Fig. 10.5 Rolling a six-sided die 6000 times.