1.5 JavaScript Functions CH - 10
1.5 JavaScript Functions CH - 10
Objectives
10.1 Introduction
• Software design
– Break software up into modules
• Easier to maintain and debug
– Divide and conquer
• 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
• 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
boss
worker4 worker5
• Function calls
– Name
– Left parenthesis
– Arguments separated by commas
• Constants, variables or expressions
– Right parenthesis
– Examples:
total += parseFloat( s1 + s2 );
• 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
• 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
• Craps
– Click Roll Dice
– Text fields show rolls, sum and point
– Status bar displays results
• Changing properties
– Access with dot (.) notation
– value property of text fields
– status property of window
• Scope
– Portion of program where identifier can be referenced
– Inside function is local or function scope
• Identifiers exist only between opening and closing braces
• Local variables hide global variables
• 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
• Global object
– Always available
– Provides 7 methods
– Do not need to explicitly reference Global before method
call
– Also holds all global variables, user defined functions
10.10 Recursion
• Recursive functions
– Call themselves
• Recursion step or recursive call
• 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
10.10 Recursion
• Factorials
– Product of calculation n · (n - 1) · (n - 2) · … · 1
– Iterative approach:
var factorial = 1;
10.10 Recursion
(a) Procession of recursive calls. (b) Values returned from each recursive call.
10.10 Recursion
Fig. 10.11 Factorial calculation with a recursive function.
• 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