cs101_lec29
TRANSCRIPT
-
7/27/2019 Cs101_Lec29
1/56
1
CS101 Introduction to Computing
Lecture 29Functions & Variable Scope
(Web Development Lecture 10)
-
7/27/2019 Cs101_Lec29
2/56
2
During the last lecture we had adiscussion onArrays
We found out why we need arrays
We became able to use arrays in conjunctionwith the for loop forsolving simple problems
-
7/27/2019 Cs101_Lec29
3/56
3
Array
An indexed list of elements
A variable is a container that holds a value
Similarly, an Array can be considered acontainer as well, but this one is more
interesting as it can hold multiple values
-
7/27/2019 Cs101_Lec29
4/56
4
Array
fruit[ 0 ]
Identifier Squarebracket
Index
-
7/27/2019 Cs101_Lec29
5/56
5
Arrays in JavaScript In JavaScript, arrays are implemented in the
form of the Array object
The key property of the Array object is length,i.e the number of elements in an array
Two of the key Array methods are: reverse( )
sort( )
Elements of an array can be of any type; you
can even have an array containing other arrays
-
7/27/2019 Cs101_Lec29
6/56
6
Todays Goal:Functions & Variable Scope
To be able to understand the concept offunctions and their use for solving simple
problems
To become familiar with some of JavaScripts
built-in functions
To become familiar with the concept oflocal
and global variables
-
7/27/2019 Cs101_Lec29
7/56
7
Function
A group of statements that is put together(ordefined) once and then can be used(by reference) repeatedly on a Web page
Also known as subprogram, procedure,subroutine
-
7/27/2019 Cs101_Lec29
8/56
8
words = new Array ( 10 ) ;
for ( k = 0 ; k < words.length ; k = k + 1 ) {words[ k ] = window.prompt( "Enter word # "+ k,"") ;
}
document.write( "UNSORTED WORDS:" + "
" ) ;for ( k = 0 ; k < words.length ; k = k + 1 ) {document.write( words[ k ] + "
") ;}
words.sort( ) ;
document.write( "SORTED WORDS:" + "
" ) ;for ( k = 0 ; k < words.length ; k = k + 1 ) {document.write( words[ k ] + "
") ;}
From the last lecture
-
7/27/2019 Cs101_Lec29
9/56
9
words = new Array ( 10 ) ;
for ( k = 0 ; k < words.length ; k = k + 1 ) {words[ k ] = window.prompt( "Enter word # " + k, "" ) ;
}
document.write( "UNSORTED WORDS:" + "
" ) ;for ( k = 0 ; k < words.length ; k = k + 1 ) {document.write( words[ k ] + "
") ;}
words.sort( ) ;
document.write( "SORTED WORDS:" + "
" ) ;for ( k = 0 ; k < words.length ; k = k + 1 ) {document.write( words[ k ] + "
") ;}
-
7/27/2019 Cs101_Lec29
10/56
10
function writeList( heading, words ) {
document.write( heading + "
" ) ;for ( k = 0 ; k < words.length ; k = k + 1 ) {document.write( words[ k ] + "
") ;}}
words = new Array ( 10 ) ;for ( k = 0 ; k < words.length ; k = k + 1 ) {
words[ k ] = window.prompt( "Enter word # "+ k,"") ;}
writeList( Unsorted Words:, words ) ;
words.sort( ) ;
writeList( Sorted List:, words ) ;
The function isdefined here
The function iscalled here and
in the next box
-
7/27/2019 Cs101_Lec29
11/56
11
Advantages of Functions
Numberof lines of code is reduced
Code becomes easier to read & understand
Code becomes easier to maintain as changesneed to be made only at a single location
instead multiple locations
-
7/27/2019 Cs101_Lec29
12/56
12
function writeList( heading, words ) {document.write( heading + "
" ) ;for ( k = 0 ; k < words.length ; k = k + 1 ) {document.write( words[ k ] + "
") ;}}words = new Array ( 10 ) ;
for ( k = 0 ; k < words.length ; k = k + 1 ) {words[ k ] = window.prompt( "Enter word # "+ k,"") ;
}
writeList( Unsorted Words:, words ) ;
words.sort( ) ;writeList( Sorted List:, words ) ;
Lets us see
if we canredouble the
advantage
-
7/27/2019 Cs101_Lec29
13/56
13
function writeList( heading, words ) {document.write( heading + "
" ) ;for ( k = 0 ; k < words.length ; k = k + 1 ) {document.write( words[ k ] + "
") ;}}words = new Array ( 10 ) ;
for ( k = 0 ; k < words.length ; k = k + 1 ) {words[ k ] = window.prompt( "Enter word # "+ k,"") ;
}
writeList( Unsorted Words:, words ) ;
words.sort( ) ;writeList( Sorted List:, words ) ;
words.reverse( ) ;
writeList( Reverse-Sorted List:, words ) ;
-
7/27/2019 Cs101_Lec29
14/56
14
function writeList( heading, words ) {
document.write( heading + "
" ) ;for ( k = 0 ; k < words.length ; k = k + 1 ) {document.write( words[ k ] + "
") ;}}
Keyword
Functionidentifier
Pair ofparenthesis
Function argumentsseparated by commas
Function
definitionenclosedin a pairof curly
braces
-
7/27/2019 Cs101_Lec29
15/56
15
Function Identifiers
The naming rules for function identifiersare the same as were discussed forvariable and array identifiers
-
7/27/2019 Cs101_Lec29
16/56
16
Arguments of a Function
A comma-separated list of data
Arguments define the interface between the
function and the rest of the Web page
Arguments values are passed to the
function by value (some popular languagespass arguments by reference as well)
-
7/27/2019 Cs101_Lec29
17/56
17
To ensure that a function is defined
before it is called up, define allfunctions in the HEAD portion of Web
pages
-
7/27/2019 Cs101_Lec29
18/56
18
Two Ways of Calling Functions
function add( a, b ) {
c = a + b ;
return c ;}
sum = add( 2, 4 ) ;
document.write( sum ) ;
function popUp( message ) {
window.alert( message ) ;}
popUp( Warning!) ;A function callappearing aspartof a statement.
Definitions of
such functionsinclude a return
statement
A function call
appearing as acomplete
statement
-
7/27/2019 Cs101_Lec29
19/56
19
function popUp( message ) {
window.alert( message ) ;}
popUp(Warning!) ;
function popUp( message ) {
window.alert( message ) ;
}a = popUp(Warning!) ;
document.write( a ) ;
What will getwritten by thisstatement?
undefined
-
7/27/2019 Cs101_Lec29
20/56
20
function add( a, b ) {
c = a + b ;
return c ;}
sum = add( 2, 4 ) ;
document.write( sum ) ;
function add( a, b ) {
c = a + b ;
return c ;
}
add( 2, 4 ) ;
What wouldthis statement
do?
function add( a, b ) {
c = a + b ;
return c ;
}
document.write(add(2,4));
What wouldthis modifica-
tion do?
-
7/27/2019 Cs101_Lec29
21/56
21
function factorial( n ) {product = 1 ;for ( k = 1 ; k
-
7/27/2019 Cs101_Lec29
22/56
22
What Would this Statement Do?
factorial( factorial ( 3 ) ) ;
This is termed as the
recursiveuse of a function
-
7/27/2019 Cs101_Lec29
23/56
23
function
method
M th d
-
7/27/2019 Cs101_Lec29
24/56
24
Methods
Methods are functions
They are unusualin the sense that they
are stored as properties of objects
Obj t
-
7/27/2019 Cs101_Lec29
25/56
25
Object:A namedcollection of properties(data, state) & methods (instructions, behavior)
prop1prop 2
prop 5
name
prop 3
prop 4
A collectionof properties& methods
All objects have thename property: it
holds the name of
the object (collection)
method 3method 1
method 2
Obj t
-
7/27/2019 Cs101_Lec29
26/56
26
Object:A namedcollection of properties
prop1prop 2
prop 5
name
prop 3
prop 4
A collectionof properties
All objects have thename property: it
holds the name of
the object (collection)
prop 7prop 6
prop 8
-
7/27/2019 Cs101_Lec29
27/56
27
function
event handler
E t H dl
-
7/27/2019 Cs101_Lec29
28/56
28
Event Handlers
Special-purpose functions that come predefined
with JavaScript
They are unusualin the sense that they aremany times called in the HTML part of a Webpage and not the part
More on event handlers in a future lecture
P d fi d T L l B ilt I F ti
-
7/27/2019 Cs101_Lec29
29/56
29
Predefined, Top-Level or Built-In Functions
Event handlers are not the only functions thatcome predefined with JavaScript. There aremany others.
Practically, there is no difference betweenpredefined functions and those that are definedby the programmer (termed as user-defined or
custom functions)
There are many of them, but here we discussonly two: parseInt( ), parseFloat( )
The dictionary
meaning of Parse:To breakdown into
simpler components
and analyze
I t( )
-
7/27/2019 Cs101_Lec29
30/56
30
parseInt( )
Syntax: parseInt ( string )
string1 =3.14159 ;
document.write( parseInt( string1 )) ;document.write(
) ;string2 =$100.00 ;
document.write( parseInt( string2 ) ) ;document.write(
) ;string3 = 23 ;
document.write( parseInt( string3 )) ;
3
NaN23
I t( )
-
7/27/2019 Cs101_Lec29
31/56
31
parseInt( )
1. Parses the string argument; returns an integer
2. If itencounters a non-numeral - anything otherthan (+,-) or (0-9) - it ignores it and allsucceeding characters, and returns theinteger value parsed up to that point
I t( )
-
7/27/2019 Cs101_Lec29
32/56
32
parseInt( )
3. If the first charactercannot be converted to anumber, parseInt returns NaN
4. parseInttruncates numbers to integervalues
5. Leading and trailing spaces are ignored
parseFloat( )
-
7/27/2019 Cs101_Lec29
33/56
33
parseFloat( )
Syntax: parseFloat ( string )
string1 =3.14159 ;
document.write( parseFloat( string1 )) ;document.write(
) ;string2 =$100.00 ;
document.write( parseFloat( string2 ) ) ;document.write(
) ;string3 = 23E-15 ;
document.write( parseFloat( string3 )) ;
3.14159
NaN2.3E-14
parseFloat( )
-
7/27/2019 Cs101_Lec29
34/56
34
parseFloat( )
1. Parses the string argument; returns a FP number
2. If it encounters a character other than
A sign (+,-)
A numeral (0-9)
A decimal point
An exponent
it returns the value up to that point, ignoringthat and all succeeding characters
parseFloat( )
-
7/27/2019 Cs101_Lec29
35/56
35
parseFloat( )
3. If the first charactercannot be converted to anumber, parseFloat returns NaN
4. Leading and trailing spaces are ignored
Scope of Variable
-
7/27/2019 Cs101_Lec29
36/56
36
Scope of Variable
Defining the space in which a variable is effective
is known as
defining the scope of a variable
A variable can beeitherlocalorglobal
in scope
L l d Gl b l V i bl
-
7/27/2019 Cs101_Lec29
37/56
37
Local and Global Variables
Local or Function-level Variable
Effective only in the function in which theyare declared
Global Variables
Visible everywhere on the Web page
function factorial( n ) { E l
-
7/27/2019 Cs101_Lec29
38/56
38
function factorial( n ) {product = 1 ;for ( k = 1 ; k
-
7/27/2019 Cs101_Lec29
39/56
39
-
7/27/2019 Cs101_Lec29
40/56
40
function factorial( n ) {
-
7/27/2019 Cs101_Lec29
41/56
41
function factorial( n ) {product = 1 ;for ( k = 1 ; k
-
7/27/2019 Cs101_Lec29
42/56
42
function factorial( n ) {product = 1 ;for ( k = 1 ; k
-
7/27/2019 Cs101_Lec29
43/56
43
function factorial( n ) {vark ;product = 1 ;
for ( k = 1 ; k
-
7/27/2019 Cs101_Lec29
44/56
44
-
7/27/2019 Cs101_Lec29
45/56
45
k is a Local Variable
-
7/27/2019 Cs101_Lec29
46/56
46
k is a Local Variable
k is not declared or used in the maincode
Instead, it is declared within the function
factorial only
k is localto the factorial function, and
does not hold any meaning outside thatfunction
function factorial( n ) {
Here product has
-
7/27/2019 Cs101_Lec29
47/56
47
function factorial( n ) {vark, product ;product = 1 ;
for ( k = 1 ; k
-
7/27/2019 Cs101_Lec29
48/56
48
Local Variables
Declaring variables (using the varkeyword) within a function, makes themlocal
They are available only within thefunction and hold no meaning outside ofit
Global Variables
-
7/27/2019 Cs101_Lec29
49/56
49
Global Variables
All other variables used in a Web page (orwindow) are global
They can be manipulated from the main code
as well as from any of the functions
They include:
All variables declared in the main codeAll variables used but not declared in the main code
All variables used but not declared in any of thefunctions defined on the Web page (or window)
-
7/27/2019 Cs101_Lec29
50/56
50
var u ;
document.write( m ) ;
var c, d ;
x = y * y ;
r = s ;
var a, b ;
p = q + 2 ;
Global Local
u a
m b
p c
q d
x
y
rs
Variables declared within functions are local; all others global
function writeList( heading, words ) {
-
7/27/2019 Cs101_Lec29
51/56
51
function writeList( heading, words ) {document.write( heading + "
" ) ;for ( k = 0 ; k < words.length ; k = k + 1 ) {document.write( words[ k ] + "
") ;}}
words = new Array ( 10 ) ;
for ( k = 0 ; k < words.length ; k = k + 1 ) {words[ k ] = window.prompt( "Enter word # "+ k,"") ;}
writeList( Unsorted Words:, words ) ;
words.sort( ) ;writeList( Sorted List:, words ) ;
words.reverse( ) ;
writeList( Reverse-Sorted List:, words ) ;
Would the functionality change if we deletethe argument words from these 4 places?
h h
-
7/27/2019 Cs101_Lec29
52/56
52
why have
local variables
why not make allvariables global
Local vs- Global
-
7/27/2019 Cs101_Lec29
53/56
53
Local vs Global
Global variables can make the logic of a Webpage difficult to understand
Global variables also make the reuse and
maintenance of your code much more difficult
HEURISTIC:
If its possible to
define a variable
as local, do it! During Todays Lecture
-
7/27/2019 Cs101_Lec29
54/56
54
During Today s Lecture
We looked at functions and their use for solvingsimple problems
We became familiar with a couple ofJavaScripts built-in functions
We became familiar with the concept oflocaland global variables
Assignment #10
-
7/27/2019 Cs101_Lec29
55/56
55
Assignment #10
Develop a Web page that includes functions
that determine the mean and median of a setof numbers stored in an array
Make sure to declare all variables that you usein the main code as well as the functions
Further information on this assignment will be provide onthe CS101 Web site
Next (the 11th) Web Dev Lecture:
-
7/27/2019 Cs101_Lec29
56/56
56
Next (the 11 ) Web Dev Lecture:Event Handling
Well learn to appreciate the concept ofeventdriven programming
We will produce solutions for simple problemsusing various event handlers