News Outline Schedule Tutorials Project Tools Links

1: What Are Functions, and why should you use them?

Functions are used in JavaScript, like in most other programming languages, to separate out sections of code which are repeated often, and allow the programmer to execute a complex piece of code repeatedly, after only having to type it in once. Also, many complex programs can be made simpler, and easier to read by moving sections of the code out to a seperate function, instead of having it sitting in the main part of the program.

2: How do you create a Function?

This is the format used to create a new function:

function function-name ( parameter list ) { declarations and statements };

In the above, the parameter list inside of the brackets is a list of variable names - these represent your new function's required parameters. If you create a function which requires three parameters, then any time you try to run it, you will also need to give it all three parameters. You can also create a function with no parameters, in which case, you just leave the brackets empty.

The function's declarations and statements are a small sub-program which can use the parameters that were given, and then usually return a result. The new function can then be accessed just like any other function in JavaScript. Here is a very simple example, which does not bother returning a value for the function:

<html> <head> <title>?</title> <script type="text/javascript" > <!-- function askUser (question,numb) { var answer; answer = window.prompt("My question is: " + question,""); document.writeln("You answered: <b>" + answer + "</b> to question " + numb + "<br />"); }; // --> </script> </head> <body> <script language="JavaScript" type="text/javascript" > <!-- askUser("What is your name?",1); askUser("What is your quest?","two"); askUser("What is your favourite colour?","3"); // --> </script> </body> </html>

In the above example, the second parameter is sent sometimes as a number, and sometimes as a string - this still works, because in JavaScript, parameters for functions do not have any type assigned to them.

3: Returning Values

In most cases, the whole point of writing a function will be to carry out some calculation or evaluation of something, and so you must return a value to the program afterwards. This is always done as the last statement in the function, with the return statement. When the program reaches a return statement, two things happen - first, the function exits, and second, the parameter of the return statement will be sent back to the program, so that it can use it. Thus, if there is any program code after the return statement, it will not be executed. For example, here is a short function, which simply returns a rough value of the math constant PI:

function pi() { return 3.14159; window.alert("This line never runs!"); };

In the above example, the function will reach the line return 3.14159;, and at that point it will stop running the function, and give back the value 3.14159 wherever the function was run. The second line inside of the function, which starts with a window.alert will never get run, because the return statement stops the function at the point where it is run.

4: Variable Scope

One important aspect of functions is what is called the scope of the variables used in them. The scope of a variable refers to where in the program the variable has meaning. For example, the parameters of a function create temporary variables, which only exist inside of the function - once the function exits, they cease to exist. Similarily, if you create a variable with a var statement inside of a function, as soon as that function exits, the variable will be deleted. These types of variables that only exist inside of the function are called local variables - the opposite of them, global variables, are the ones with var statements outside of any functions - they will exist for as long as the browser is on the page they are created on.

Consider the following program:

<html> <head> <title>?</title> <script type="text/javascript" > <!-- var inp1, inp2, out1; var answer = 27; function pythag (sideA, sideB) { var answer,num1,num2; num1 = parseFloat(sideA); num2 = parseFloat(sideB); answer = Math.sqrt( (num1 * num1) + (num2 * num2) ); return answer; }; // --> </script> </head> <body> <script type="text/javascript" > <!-- inp1 = window.prompt("What is the length of side A?",""); inp2 = window.prompt("What is the length of side B?",""); out1 = pythag(inp1, inp2); document.writeln("Your right-angled triangle has sides that are " + inp1 + " and " + inp2 + " long.<br />"); document.writeln("Your right-angled triangle's hypotenuse is " + out1 + " long."); document.writeln("<hr />"); document.writeln("My triangle has sides that are 3 and 4 long.<br />"); out1 = pythag(3,4); document.writeln("My triangle's hypotenuse is " + out1 + " long.<br />"); document.writeln("The variable answer now contains: " + answer); // --> </script> </body> </html>

The variables marked like this above are what are called global variables - even though they are not used inside of the function, they could be. Except for some special cases though, this is considered a bad programming practice, so it is usually not done. Most of the time, any information you want your function to use should always be passed into it in the parameters.

The variables marked like this are what are called local variables in the function, so anything done to them will not affect variables on the outside of the function, even if they have the same name. This is why the global variable answer still has 27 in it at the end of the program, even though the local version of answer inside of the function has changed twice. The variables are not the same, despite having the same name. This is also a very good reason to keep your variable names unique - if you never have two variables with the same name as in the above program, you'll never have to worry about which one is being used.

Here are a few examples demonstrating the differences between global and local variables:

<html> <head> <title>?</title> </head> <body> <pre><script type="text/javascript" > <!-- function globalVars () { num1 = num1 * 10; num2 = num2 + 100; document.writeln("In Function globalVars, num1 = " + num1); document.writeln("In Function globalVars, num2 = " + num2); }; var num1 = 3, num2 = 7; document.writeln("Initially, num1 = "+ num1); document.writeln("Initially, num2 = "+ num2); document.writeln("--- Entering Function globalVars: ---"); globalVars(); document.writeln("After the function, num1 = "+ num1); document.writeln("After the function, num2 = "+ num2); // --> </script></pre> </body> </html>

In the above code, num1 and num2 are used as global variables - they are created outside of the function, they are given an initial value outside of the function, and changing them inside of the function changes the original version of the variable - if we ran the function twice, the changes would be made again (num1 would be multiplied by 10 again, making 300, and num2 would gain another 100, making 207.) Global variables are accessible anywhere in the program.

<html> <head> <title>?</title> </head> <body> <pre><script language="JavaScript" type="text/javascript" > <!-- function localVars () { var num1,num2; num1 = 1; num2 = 10; document.writeln("In Function localVars, num1 = "+num1); document.writeln("In Function localVars, num2 = "+num2); }; var num1 = 3, num2 = 7; document.writeln("Initially, num1 = "+ num1); document.writeln("Initially, num2 = "+ num2); document.writeln("--- Entering Function localVars: ---"); localVars(); document.writeln("After the function, num1 = "+ num1); document.writeln("After the function, num2 = "+ num2); // --> </script></pre> </body> </html>

In the above code, num1 and num2 are used as local variables - global versions were created outside of the function, but new, local versions were also created inside of the function with var statements, and values were assigned to them. These local versions will be used instead of the global ones whenever num1 or num2 are accessed inside of the function. Since the variables being used are local, when the function is finished, they are erased, and on the outside of the function we again have access to the original global versions of those variables.

5: Dealing with parameters

The parameters of the function are also considered to be local variables - they are actually just copies of the original parameters that were passed in, so changing them after the function has started will not affect the outside of your function. (Unless you're using Arrays, but we'll cover that in the next section.) If we use parameters in the examples from the previous section, it will look like this:

<html> <head> <title>?</title> </head> <body> <pre><script language="JavaScript" type="text/javascript" > <!-- function paramVars (A, B) { A = A * 20; B = B + 200; document.writeln("In Function paramVars, num1 = "+num1); document.writeln("In Function paramVars, num2 = "+num2); document.writeln("-- Also --"); document.writeln("In Function paramVars, A = "+ A); document.writeln("In Function paramVars, B = "+ B); return 1; }; var num1 = 3, num2 = 7; document.writeln("Initially, num1 = "+ num1); document.writeln("Initially, num2 = "+ num2); document.writeln("--- Entering Function paramVars: ---"); paramVars(num1,num2); document.writeln("After the function, num1 = "+ num1); document.writeln("After the function, num2 = "+ num2); // --> </script></pre> </body> </html>

Here, the variables num1 and num2 are being passed into the function as parameters, and those parameters are being changed. The changes made are accessible inside of the function, but they do not effect the original variables, which can even be accessed as global variables while inside of the function.

The parameter list creates the local variables that will hold the parameters, and copies the given data into them for you. It is very important that you never create a new local variable with the same name as your parameters - in some browsers, this will stop you from being able to access your parameters! Here is an example of that happening:

function goodFunc (A, B) { // this is good. document.write("<h2>goodFunc: " + A + B + "</h2>"); }; function badFunc (A, B) { var A, B; // This is bad! Old browsers will lose the parameters. document.write("<h2>badFunc: " + A + B + "</h2>"); }; function worseFunc (var A, var B) { // This function will crash javascript!!! document.write("<h2>worseFunc: " + A + B + "</h2>"); };

In our first function, goodFunc, we used the parameters properly - just give their names, and use them inside of the function. Javascript will take care of creating the local variables for you.

In badFunc, we over-wrote our parameters with new versions of the variable with that name. Some older browsers will not be able to access them! The official specification for JavaScript states that this should cause a JavaScript runtime error. (ie: it should crash your program.) Some newer browsers have been designed to work around it, and pretend that you didn't really do that, but you can not rely on your customer using the latest version of anything to look at the site you are creating for them, much less one particular type of browser. If it crashes on their computer, they won't pay you.)

The third function, worseFunc is the worst error of all - this will result in a Javascript error, and will stop the browser from even running any further Javascript on that page. NEVER put a var statement in the parameter list for a function!

6: Recursion

Sometimes a function can be greatly simplified by making it refer to itself - the most common example of this would be a program which calculates factorials:

<html> <head> <title>?</title> <script language="JavaScript" type="text/javascript" > <!-- function factorial(inpVar) { var num1 = parseInt(inpVar); if (isNaN(num1)) return 0; if (num1 <= 1) return 1; return num1 * ( factorial( num1 - 1 ) ); }; // --> </script> </head> <body> <script language="JavaScript" type="text/javascript" > <!-- var inp1; inp1 = window.prompt("Give me a number to factorialize:",""); document.writeln("The factorial of "+inp1+" is "+ factorial(inp1) ); // --> </script> </body> </html>

Important Note! When you create a recursive function, you MUST have some case in which it does not call itself - this is called an exit case, and without it, your program will go into an infinite loop, and in most cases, it will crash your web browser. In the above program, there are in fact, two exit cases, one if num1 is not actually a number (which will return a value of 0), and the other if the number is 1 or less, which should always return a 1.