Functions

Functions provide a mechanism for defining several lines of script that are grouped together into a single named unit.


function funName() {
    statement;
    statement;
    statement;
      ...
}
            
Functions optionally receive parameter values passed inside the brackets following the function name to be substituted for values inside the function. A comma separated list is used for multiple parameters.
function funName(a, b ,x, y, ...) {
    statement;
    statement;
    statement;
      ...
}
            

Parameter passing allows the user to reuse the same set of script lines with different data values.

Variables declared within a function are only visible to that function and are called local variables. Functions can use local and global variables.

Local variables are set back to their initial value every time the function is invoked.
The scope of a variable is the current function or, for variables declared outside a function, the current document. Variables declared outside a function are available to all functions in the current application and are called global variables.

function funName( a, b, c) {

    var d, e, f;   //local variables

    statement;
    statement;
    statement;
      ...
}
            

Functions have the option of returning a single value when they finish via the optional return statement.

General Syntax

function funName (parameter list) {
    statement;
    statement;
    statement;
      ...
    return variable
}
            
funName is the name given to the function and must be a valid identifier name using the same naming rules as variables.

eg.
<script type="text/javascript"  >

    function sayHello(){
            alert(" hello " );
    }

    function showMessage( msg ){
      alert( "message= " + msg );
    }

    function square( x ){
       var answer = x*x;
       return answer;
    }

    function demo( n ){
      var result = square(n);
      var myMessage = "The square of " + n + " is " + result;
      showMessage( myMessage );
    }

</script>

                
<script type="text/javascript">
      sayHello();
                            
      var number = 7;
      demo(number);
                            
      number = 3;
      demo(number);
                            
      showMessage( "hi there");
</script>
                            

User defined functions are useful for repeating the same sequence of actions on different data sets. A function is optionally allowed to return a data value at the completion of the function.

eg.
<script>

   function circleArea( radius ){

        var area = Math.PI*radius*radius;
        return area;
    }



    for ( var r=0; r<=100; r=r+10){

        areaOfCircle = parseInt(circleArea( r ));

        document.writeln( "radius =" + r + ", area = " + areaOfCircle+"<br />");

    }

    document.writeln("final value of radius =" + r);

</script>

                

Results:

 <script type="text/javascript">

 function fuelBill( fuelType, quantity){

   var cost;

   // fuel Prices in dollars
   var lpGasPrice    = 0.419;
   var unleadedPrice = 1.39;
   var dieselPrice   = 1.49;

   var fuelPrice;

   switch ( fuelType ){

     case "lpGas"           : fuelPrice = lpGasPrice;
                              break;

     case "Unleaded"        : fuelPrice = unleadedPrice;
                              break;

     case "Diesel"          : fuelPrice = dieselPrice;
                              break;

     default                : fuelPrice = 0;

   }

   cost = fuelPrice * quantity;

   return cost;
 }
 </script>

            

<form name="myform" method="get"
  onSubmit="dueAmount.value=fuelBill( fuelType.value,litres.value);return false;">

  <input type="hidden" value="" name="fuelType" />

  <input type="radio" value="lpGas" name="fuel"
   onClick="fuelType.value=this.value;" /> LP Gas<br />

  <input type="radio" value="Unleaded" name="fuel"
   onClick="fuelType.value=this.value;" /> Unleaded<br />

  <input type="radio" value="Diesel" name="fuel"
   onClick="fuelType.value=this.value;" /> Diesel<br />

  <input type="text" size="10" name="litres" value="" /> litres<br />

  <input type="text" size="10" name="dueAmount"
       onFocus="this.blur()" /> dollars<br />

  <input type="submit" value="calculate" />
  <input type="reset" value="reset" onClick="litres.value=0;fuelType.value=''" />

</form>
            
LP Gas
Unleaded
Diesel
litres
dollars

OnSubmit notes


To round a number to a fixed number of digits following the decimal point, use number.toFixed(fractionDigits) as defined in ECMA Script-262

eg.
     var n;
     var m;

     n = 13.45639;
     m = n.toFixed(0); // rounds to nearest whole number
                       // ie. 13

     m = n.toFixed(1); // rounds to 1 decimal places after decimal point
                       // ie. 13.5

     m = n.toFixed(2); // rounds to 2 decimal places after decimal point
                       // ie. 13.46

     m = n.toFixed(3); // rounds to 3 decimal places after decimal point
                       // ie. 13.456

     m = n.toFixed(4); // rounds to 4 decimal places after decimal point
                       // ie. 13.4564

     m = n.toFixed(5); // rounds to 5 decimal places after decimal point
                       // ie. 13.45639
            
Here is a more complicated function that Mal Sutherland wrote in the old days to round a number to a fixed number of decimal places and to pad trailing zeroes to the end of the number.

function formatNumber( n, places){

// the formatNumber function returns a formatted String equivalent of a
// numeric data item "n" by rounding to the number of decimal places
// given by the "places" parameter.
//
// Author: Mal Sutherland
// Date  : 22-Aug-2000
//
    if (isNaN(parseFloat(n)) ) return parseFloat(n);

    var numberString;
    var roundingFactor = Math.pow( 10, places);
    var sign = n<0?"-":"";

    n = Math.abs(n);

    n = Math.round(n*roundingFactor)/roundingFactor;

    numberString = n.toString();

    if( numberString.indexOf(".") == 0)
       numberString = "0" + numberString ;


    if ( numberString.indexOf(".") < 0)
          numberString = numberString + ".0";

    numberString+=Math.pow( 10, places).toString().substr(1);
    numberString = numberString.substring(0,numberString.indexOf(".")+places+1);

    return sign+numberString;
}
            

User Defined Functions

We have seen that functions can be used to define a collection of javascript statements that perform a specialized task

or calculate and return the result of some calculation. eg.

 Calculate and return the area of a circle based on information
    passed to the function as a parameter.

<script>
    function areaOfCircle(radius){

      var area;

      area = Math.PI*radius*radius;

      return area;

    }
</script>


<script>
  var areaA = areaOfCircle(2.0);
  var areaB = areaOfCircle(1.7);

  document.writeln( "areaA = " + areaA +"<br />" );
  document.writeln( "areaB = " + areaB +"<br />" );
</script>
            
enter radius
area
<form name="myForm" onSubmit="return false;">

 enter radius <input type="text" name="radius" /><br />

 area <input type="text" name="result" /><br />

 <input type="button" value="calculate"
        onClick="result.value= areaOfCircle(radius.value)" />

</form>
            
Notes:
The action is performed via the "calculate" button using an onClick
event handler.

Again, the document object model is used to access field values.

onSubmit="return false;" is used to stop the form from being submitted
when the user presses the [enter] key in a text field. Without this code, the
default action ( url base for this page ) would be sent the form results.

External Functions

Utility functions that could be used by several web documents can be stored in an external file.

The convention is to add a ".js" extension to the file name such as "myFunctions.js"

The external file contains only Javascript and no html markups including the script tag.

eg. "myFunctions.js"


    function areaOfCircle(radius){

      var area;

      area = Math.PI*radius*radius;

      return area;
    }



    function areaOfRectangle(length, width){

      var area;

      area = length*width;

      return area;

    }
                

Importing Functions


To use the functions defined in an external javascript file named "myFunctions.js" use the src attribute of the <script> tag as follows:

eg. "demo.html"
 <html>
    <head>

        <script  type="text/javascript" src="myFunctions.js"> </script>

    </head>

    <body>

       <script>
           var areaA = areaOfCircle(2.0);
           var areaB = areaOfCircle(1.7);

           document.writeln( "AreaA = " + areaA +"<br />" );
           document.writeln( "AreaB = " + areaB +"<br />" );
       </script>


    </body>

 </html>
                

Hiding javascript

Hiding javascript code from browsers that don't support javascript

<script type="text/javascript">
<!-

         Your javascript code goes here

//-->
</script>

<noscript>
       your browser does not support javascript <br />
       to see the javascript functionality of this web page you need to either <br />
        <ul>
            <li>enable javascript in your preferences OR </li>
            <li>update your browser </li>
        </ul>
</noscript>
            

© 2009 Mal Sutherland