














































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!















































During the last lecture we had a discussion on Arrays
Array
4
fruit[ 0 ]
Identifier Square bracket
Index
Arrays in JavaScript
Function
A group of statements that is put together (or defined) once and then can be used (by reference) repeatedly on a Web page
Also known as subprogram, procedure, subroutine
words = new Array ( 10 ) ; From the last lecture …
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 ] + "
" ) ; } (^) Docsity.com 8
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 ) ; 10
The function is defined here
The function is called here and in the next box
Advantages of Functions
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 ) ; (^13)
function writeList( heading, words ) {
document.write( heading + "
" ) ;
for ( k = 0 ; k < words.length ; k = k + 1 ) { document.write( words[ k ] + "
" ) ; } } 14
Keyword
Function identifier
Pair of parenthesis
Function ‘arguments’ separated by commas
Function definition enclosed in a pair of curly braces
Arguments of a Function
To ensure that a function is defined before it is called up, define all functions in the HEAD
portion of Web pages
19
function popUp( message ) {
window.alert( message ) ;
}
popUp( “Warning!” ) ;
function popUp( message ) { window.alert( message ) ; } a = popUp( “Warning!” ) ; document.write( a ) ;
What will get written by this statement?
undefined
function add( a, b ) {
c = a + b ; return c ;
}
sum = add( 2, 4 ) ;
document.write( sum ) ;
20
function add( a, b ) { c = a + b ; return c ; } add( 2, 4 ) ;
What would this statement do?
function add( a, b ) { c = a + b ; return c ; } document.write( add( 2, 4 ) ) ;
What would this modifica- tion do?