![]() | MSc-IT Study Material June 2010 Edition Computer Science Department, University of Cape Town |
The following lines illustrate the use of built-in functions:
document.write( "Hello" ); document.write( Math.sqr( 2 ) ); document.write( "The bigger of 4 and 5 is : " + Math.bigger(4, 5) );
You can define your own functions in the same file that they are invoked in, or in a different file which you can then load in a browser whenever you wish to use the function. Each of these situations are illustrated below.
The following code defines and invokes a function named displayHello:
<HTML> <SCRIPT> ///////////////////////////// /// define function here /// ///////////////////////////// function displayHello() { document.write( "Hello" ) } ///////////////////////////// /// invoke function here /// ///////////////////////////// displayHello(); </SCRIPT> </HTML>
The browser output when this HTML file is loaded is as follows:
Some functions prove very useful; in order to use them in multiple Web pages they can be stored in a separate file. In the example below, the function displayHello has been defined in the file helloFunction.js. The HTML below uses two <SCRIPT> tags, one to load the function definition from helloFunction.js, and the second to invoke the function:
<SCRIPT SRC="helloFunction.js"></SCRIPT> <SCRIPT> <!-- /// invoke function here /// displayHello(); </SCRIPT> -->
The contents of the file helloFunction.js is simply the JavaScript definition of the function:
/// define function here /// function displayHello() { document.write( "Hello" ) }
Notice that helloFunction.js is not an HTML file and does not contain any HTML tags. This is signified by choosing an appropriate file extension — the convention is to use the two-character extension ".js" for JavaScript files.
The eval operator expects a String containing JavaScript as an argument, and will execute the String as if it where a JavaScript statement. The code below creates a String named myStatements and then executes the String using eval:
var myStatements = " var n = 10; alert( n ); n++; alert( n ) " ; eval( myStatements );
The result of executing this code is the two alert dialogs: