Using Functions

A function is a set of commands, with a name, that you can execute by calling that name and passing in any parameters that the function requires. You usually use functions when you have a set of commands that you want to be able to repeat at different places in your script, rather than at one place like with a loop. Let us look at an example:

function timesTen(number) { 
 result = number * 10; 
 return result; 
} 
myNumber = timesTen(5); 
aa.print(myNumber); 

This script displays this output:

50

The first four lines of the script create the function. The fifth line stores the function result in a variable and the sixth line uses the variable value as a parameter. We call the four lines that create the function the definition of the function. You can place your function definitions at the beginning or end or your scripts.

Function definitions begin with the word “function” followed by a space, then the name of the function. We can see that the function name is “timesTen”. After the function name is a pair of parentheses that enclose the parameter list for the function. We can see that there is one parameter called “number.” You can declare as many parameters as you like, but you must separate each one by a comma. Note that parameter names must follow the same rules as variable names.

After the parameter list is a block of one or more commands, enclosed by a pair of braces. The first line in this block for the timesTen function takes the number parameter, multiplies it by ten, and puts the result in the result variable. The second line begins with the keyword “return.” This keyword means “send back to whoever called this function the following value.” The value following the word “return” on the second line of this script is the variable result. So when one calls the timesTen function, it takes its first parameter, multiples it by ten, and gives as a result the value of the result of that command.

We can see the sixth line of the script calls the timesTen function and the value five passes in as its parameter. The script assigns the result of the timesTen function to the value of the myNumber variable. The last line of the script prints out the value.