Chapter 10: JavaScript Functions CIS 275—Web Application Development for Business I
2 Program Modules in JavaScript Software development is best achieved in smaller pieces called _________, applying the principle of “divide and conquer”. A module in JavaScript is called a _________. A pre-defined function that belongs to a class is called a method (like Math.pow or Math.round). A function you write is called a ____________- defined function. A function is invoked by a function call. A function call may include arguments. A called function may _______ data to the caller.
3 Programmer-Defined Functions All variables declared in a function are _______. A function declaration may include parameters, which are also local variables. Functions enable the principle of software reuse and help to avoid code repetition. Format of a function definition function function-name ( parameter-list ) { declarations and statements } The ___ is the function call operator. The first line is the function declaration and the content within the {}’s is the function ______. ()
4 Fig A Programmer-Defined Function document.writeln( " Square numbers from 1 to 10 " ); for ( var x = 1; x <= 10; ++x ) document.writeln( "The square of " + x + " is " + square( x ) + " " ); function square( y ) // do NOT use var here { return y * y; }
5 Example of a Function Call function myFunction(){ alert("HELLO") } <input type = "button" onclick = "myFunction()" value = "Call function" > By pressing the button, a function will be called. The function will alert a message.
Function Call w/ Arguments and Return <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " function total(numberA, numberB){ return numberA + numberB } document.write( total(2,3) )
Scope Rules The scope of an identifier for a variable or function is the part of the program in which the identifier can be referenced. Variables declared in the ______ element are global variables and have global scope. Variables declared inside a function have ______ scope and can be used only in that function. Function parameters also have local scope. A variable with local scope will ______ a variable with the same name that has global scope.