Functions

Functions are basically ways of executing many lines of codes with in one line (or less); like a mini-program. Let's say for example you have to constantly do something like this:

  if(confirm("Is this the correct value?")) {
    top.frame1.document.open();
    top.frame1.document.write("You chose wisely...");
    top.frame1.document.close();
  }
Don't worry about understanding what this does. We're just using it for an example.

So, instead you can create a function where you can pass it some values. Below you will the syntax of a function:

 function function_name(parameter_1, parameter_2, ... parameter_n){
   line_1;
   line_2;
   .
   .
   .
   line_n;
 }
So, whenever this function is called it will execute the lines of code between the { }'s. Here is an example of using a function for the above example:
  function Iamlazy (output_string){
    if(confirm("Is this the correct value?")) {
      top.frame1.document.open();
      top.frame1.document.write(output_string);
      top.frame1.document.close();
    }
  }
Functions are executed when someone makes a reference to them by calling their name followed by their parameters in parentheses. For the above example you would reference it with the following:
Iamlazy("You chose wisely...");
With functions, they give you increased power, so you can output anything you want. As in:
Iamlazy("You chose poorly...");
So you can define the function once, and call it many times with any different value you wish.

Don't forget that you should put functions into the <HEAD> part of the document so that they are loaded first.

You may notice that there is no type-checking. That's because JavaScript is a very loose language. You never have to specify what type of variable something is. This can be a blessing or a curse.

Returning Values

Your function can return a value. Just use the return statement.
  return(some_value);
Note that the function exits as soon as it hits the return statement.
Return to Front Page
Continue to next section: Statements