Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Function Definitions - JavaScript(JS)

# Function Definitions - JavaScript(JS)

Each script we have presented thus far in the text has consisted of a series of statements and control structures in sequence.

Function Definitions

Each script we have presented thus far in the text has consisted of a series of statements and control structures in sequence. These scripts have been executed as the browser loads the web page and evaluates the <head> section of the page. We now consider how you can write your own customized functions and call them in a script.

Programmer-Defined Function square

Consider a script (Fig. 9.2) that uses a function square to calculate the squares of the in-tegers from 1 to 10. [Note: We continue to show many examples in which the body ele-ment of the XHTML document is empty and the document is created directly by JavaScript. In later chapters, we show many examples in which JavaScripts interact with the elements in the body of a document.]

The for statement in lines 15–17 outputs XHTML that displays the results of squaring the integers from 1 to 10. Each iteration of the loop calculates the square of the current value of control variable x and outputs the result by writing a line in the XHTML document. Function square is invoked, or called, in line 17 with the expression square(x). When program control reaches this expression, the program calls function square (defined in lines 23–26). The parentheses () represent the function-call operator, which has high precedence. At this point, the program makes a copy of the value of x (the argument) and program control transfers to the first line of function square. Function square receives the copy of the value of x and stores it in the parameter y. Then square calculates y * y. The result is passed back (returned) to the point in line 17 where square was invoked. Lines 16–17 concatenate "The square of ", the value of x, the string " is ",

<?xml version = "1.0" encoding = "utf-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 9.2: SquareInt.html -->

<!-- Programmer-defined function square. -->

<html xmlns = "http://www.w3.org/1999/xhtml">

<title>A Programmer-Defined square Function</title>

<script type = "text/javascript">

<!--

document.writeln( "<h1>Square the numbers from 1 to 10</h1>" );

// square the numbers from 1 to 10

for ( var x = 1; x <= 10; x++ )

document.writeln( "The square of " + x + " is " +

square( x ) + "<br />" );

// The following square function definition is executed

// only when the function is explicitly called.

// square function definition

function square( y )

{

return y * y;

} // end function square

// -->

</script>

</html> Fig. 9.2 | Programmer-defined function square.

the value returned by function square and a <br /> tag and write that line of text in the XHTML document. This process is repeated 10 times.

The definition of function square (lines 23–26) shows that square expects a single parameter y. Function square uses this name in its body to manipulate the value passed to square from line 17. The return statement in square passes the result of the calculation y * y back to the calling function. Note that JavaScript keyword var is not used to declare variables in the parameter list of a function.

In this example, function square follows the rest of the script. When the for state-ment terminates, program control does not flow sequentially into function square. A function must be called explicitly for the code in its body to execute. Thus, when the for statement terminates in this example, the script terminates.

The format of a function definition is

function function-name( parameter-list )

{

declarations and statements

}

The function-name is any valid identifier. The parameter-list is a comma-separated list con-taining the names of the parameters received by the function when it is called (remember that the arguments in the function call are assigned to the corresponding parameter in the function definition). There should be one argument in the function call for each parame-ter in the function definition. If a function does not receive any values, the parameter-list is empty (i.e., the function name is followed by an empty set of parentheses). The declara-tions and statements in braces form the function body.

There are three ways to return control to the point at which a function was invoked. If the function does not return a result, control returns when the program reaches the function-ending right brace or by executing the statement

return;

If the function does return a result, the statement

return expression;

returns the value of expression to the caller. When a return statement is executed, control returns immediately to the point at which the function was invoked.

Programmer-Defined Function maximum

The script in our next example (Fig. 9.3) uses a programmer-defined function called max-imum to determine and return the largest of three floating-point values.

The three floating-point values are input by the user via prompt dialogs (lines 12–14). Lines 16–18 use function parseFloat to convert the strings entered by the user to floating-point values. The statement in line 20 passes the three floating-point values to function maximum (defined in lines 28–31), which determines the largest floating-point value. This value is returned to line 20 by the return statement in function maximum. The value returned is assigned to variable maxValue. Lines 22–25 display the three floating-point values input by the user and the calculated maxValue.

Note the implementation of the function maximum (lines 28–31). The first line indi-cates that the function’s name is maximum and that the function takes three parameters (x, y and z) to accomplish its task. Also, the body of the function contains the statement which returns the largest of the three floating-point values, using two calls to the Math object’s max method. First, method Math.max is invoked with the values of variables y and z to determine the larger of the two values. Next, the value of variable x and the result of the first call to Math.max are passed to method Math.max. Finally, the result of the second call to Math.max is returned to the point at which maximum was invoked (i.e., line 20). Note

<?xml version = "1.0" encoding = "utf-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 9.3: maximum.html -->

<!-- Programmer-Defined maximum function. -->

<html xmlns = "http://www.w3.org/1999/xhtml">

<title>Finding the Maximum of Three Values</title>

<script type = "text/javascript">

<!--

var input1 = window.prompt( "Enter first number", "0" );

var input2 = window.prompt( "Enter second number", "0" );

var input3 = window.prompt( "Enter third number", "0" );

var value1 = parseFloat( input1 );

var value2 = parseFloat( input2 );

var value3 = parseFloat( input3 );

var maxValue =  maximum( value1, value2, value3 )       ;

document.writeln( "First number: " + value1 +

"<br />Second number: " + value2 +

"<br />Third number: " + value3 +

"<br />Maximum is: " + maxValue );

// maximum function definition (called from line 20)

function maximum( x, y, z )

{

return Math.max( x, Math.max( y, z ) );

} // end function maximum

// -->

</script>

<body>

<p>Click Refresh (or Reload) to run the script again</p>

</body>

</html>  Fig. 9.3 | Programmer-defined maximum function.

once again that the script terminates before sequentially reaching the definition of func-tion maximum. The statement in the body of function maximum executes only when the function is invoked from line 20.

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Related Topics