Topics

Function

A function is a JavaScript construct with the following properties

One benefit of using functions is that it allows the programmer to encapsulate a behavior. This behavior may be invoked repeatedly without duplicating the code. All that is needed is to call the function.

From previous day, a function definition would be

      
      function swapcb(a,b)
      {
         var temp;
         temp = a.checked;
         a.checked = b.checked;
         b.checked = temp;
      }

      
And a call to this function would be
      
      swapcb(document.ex1.ppp,document.ex1.qqq)

      
Note how the information (object) is passed into the function and referred to by a different set of names. Demo

The general syntax is of the form

      
         function FunctionName(Param1,Param2,...)
         {
            Statements
         }

      
where

A function can return a value upon completion using the return statement.

      
      function sq_add_5(x)
      {
         x = x * x + 5;
         return x
      }
      
      z = 3;
      y = sq_add_5(z);
      alert('Value of Y is ' + y );

      

Function Definition

Two function calls may have different results by supplying different arguments.

       
           function put_in_box1(in_val) 
           { 
              document.game.door1.value = in_val; 
           } 
           . . . 
           put_in_box(12); 
           . . . 
           put_in_box("words to use"); 
           . . . 
         
The first call will put 12 in as the new value for text box door1.

The second will assign the string words to use to the box By passing objects to functions, the functions can operate on many different objects. As in the Swap-Checkbox example.