Extra Help on functions

You can declare local variables the normal way, i.e. using

var variableName;
var anotherVariable = 2;   // etc.

inside a function. These variables exist only while the function is running. When the function has finished (either a return statement has been carried out, or the program reaches the curly bracket at the end of the function), any variables declared inside it die and disappear. If you try to refer to these variables in the outside program, it will cause an error. Here's an example:

<SCRIPT LANGUAGE="JavaScript">
function add_on_r ()
{ var r = 100;
  a += r;
}

var a = 0;
add_on_r();
document.write("a is " + a + "<br />");
document.write("r is " + r + "<br />");
</script>

In this case, the function can use two varaibles, a and r. a is called a global variable as it has been declared in the outside program, which means that it can be used anywhere in the program - in the main program or inside a function. On the other hand, the variable r can only be used and referred to inside the function, as it has been declared inside the function.

The first document.write() statement works perfectly - it displays the value of a. However, the second document.write() statement causes an error as it tries to refer to the value of r:

Undeclared variable error

In short, when a function comes across a variable name, it will search for the variable as follows:

  • Firstly, it searches amongst its own local variables. If the variable name is found, then the search for the variable is over - the function has found the one it is going to use.
  • If the variable isn't among the local variables, then the function moves out one stage. If it was called from within another function (e.g. another function called this one), then the program will search among the local variables of that function.
  • Only if the function still can't find the variable amongst the local variables will it look for the variable in the outside program. If it still can't find the variable, then the variable doesn't exist - the function reports an error!

So what happens if the variables declared locally inside the function have a name which clashes with a variable in the outside program? In that case, the function creates its own version of the variable and used that one instead of the one in the main program. For example, consider this program:

<script language="JavaScript">
var size = 2;
alter_size();
document.write("The value of size is now " + size + "<br />");

function alter_size ()
{ var size = 2;
  size = (100 - size) * 50 * (size + 1);
}
</script>

It looks as if the function really messes around with the value of the variable size, doesn't it! In fact, the value that is displayed is still 2. This is because the variable whose value is displayed is never altered at all! The variable whose value was changed was the one within the function alter_size().

The same thing applies to parameters. If there is a variable in the main program with the same name, then the function ignores it and just deals with the parameter value. Here, is the obligatory example:

<script language="JavaScript">
var myValue = 47;
messAround(103.5);
document.write("The value of myValue is now " + myValue + "<br />");

function messAround (myValue)
{ myValue += 230;    // Add 230 on to myValue
  document.write("Inside the function myValue is " + myValue + "<br />");
}
</script>

The program displays the message Inside the function myValue is 333.5 followed by the message The value of myValue is now 47 on a separate line. This means that the addition which is the first line of the function has not been carried out on the variable myValue in the outside program, but on the parameter instead. When the function finished, the parameter died with it and the value of 333.5 disappeared from the program.

Look at the program in the previous example (the one with the parameter called myValue). It may seem strange that the first message to appear on the screen is the one that starts with Inside the function .... After all, this line only appears in the web page file after the instruction for displaying the other message.

Program flow for a function

You must remember that when the program comes across a function call, the entire flow of the program changes. It jumps to wherever the start of the function definition is, whether it was defined before the main program or after it, and then start executing statements from there. When the function finishes, the program takes up again where it left off - with the statement after the original function call.

There is no reason why an array can't be declared within a function as a local variable, just as a simple variable can be. The declaration is done exactly as it would be in the outside program:

function normal (mean)
{ var values = new Array();
  var count;
  for (count = 0; count < 10; count++)
   values[count] = Math.floor(Math.random() * 6);
  var sum = 0;
  for (count = 0; count < 10; count++)
   sum += values[count];
  return sum - 30 + mean;
}

The function that you see defined above is used to give a random number which is approximately normally distributed about a given central point (the value of the parameter mean. It uses a local array, called values which ceases to exist at the moment when the function has executed the return statement.

The same rules apply to local arrays as to ordinary local variables. If the function contains an instruction to define an array variable with the same name as one in the outside world, the variable outside the function is marked as out of bounds until the function finishes - the function will alter or refer to its own variable with that name.

The browser automatically knows where the functions are as the function definitions are contained within the curly brackets after the word function. Anything which is not inside the curly brackets of a function definition must be part of the main program and the browser treats it as such.

By a block of code here I mean a code segment inside <script> and </script> tags. It is perfectly possible to insert two (or more) JavaScript code blocks, to define the function in one block of code and to call the function in the other block:

<script language="JavaScript">
// Here is a function definition
function myFunction (par)
{ // Statements that make up the function definition
}
</script>

This is a web page, outside the SCRIPT tags
for JavaScript. <hr />

<h1>Some time later...</h1>

<script language="JavaScript">
// And here is the function call itself!
myFunction(23);
</script>

There may be large amount of HTML between the two blocks of JavaScript, but the function can be called between one block and the other. You will find if you look at commercial web sites or sites developed by experienced browsers that this is quite a common occurrence.

You will notice by comparing the examples that you see above with others dotted around this tutorial that sometimes I call a function and then define it later in the program, and sometimes I define the function first and then call it later. JavaScript doesn't really care which of these you do, as long as it can always find a function definition when it comes across a call to that function.

One or two other programming languages are just as easy going, such as Java or BASIC. They don't really care whether the call or the definition comes first. However, languages such as C++ and Pascal insist that a function is defined before it is called.

Consider this program fragment:

function sgn (number)
{ if (number > 0)
   return 1;
  if (number < 0)
   return -1;
  return 0;
}

This function implements the mathematical function called SGN which translates any positive number into +1, any negative number into -1, and leaves 0 unchanged. It therefore gives the sign of the number. The thing of interest is the program flow through the function. If the first condition is true (the number is bigger than 0), then the function hits the return 1 statement and immediately terminates, handing back 1 to the calling program. The other if statement and the return 0 at the end are ignored.

If the number is not bigger than 0, then first if condition fails. The program flow then continues with the next if to test whether the number is less than 0. If it is, then the function hits return -1 and immediately terminates, handing back -1 to the program.

Only if the number is 0, i.e. both conditions fail, does the function ever reach the return 0 statement. This causes the function to terminate, handing back 0 to the calling program.