User Guide

48 Chapter 2: ActionScript Basics
In the following example, the variable inValue contains a primitive value, 3, so that value is
passed to the
sqr() function and the returned value is 9:
function sqr(x:Number):Number {
var x:Number = x * x;
return x;
}
var inValue:Number = 3;
var out:Number = sqr(inValue);
trace(inValue); //3
trace(out); //9
The value of the variable inValue does not change, even though the value of x in the function
changes.
The object data type can contain such a large amount of complex information that a variable with
this type doesnt hold an actual value; it holds a reference to a value. This reference is similar to an
alias that points to the contents of the variable. When the variable needs to know its value,
the reference asks for the contents and returns the answer without transferring the value to
the variable.
The following example shows passing by reference:
var myArray:Array = ["tom", "josie"];
var newArray:Array = myArray;
myArray[1] = "jack";
trace(newArray); // tom,jack
This code creates an Array object called myArray that has two elements. The variable newArray is
created and is passed a reference to
myArray. When the second element of myArray is changed to
"
jack", it affects every variable with a reference to it. The trace() statement sends tom,jack to
the Output panel. Flash uses a zero-based index, which means that 0 is the first item in the array,
1 is the second, and so on.
In the following example,
myArray contains an Array object, so it is passed to function
zeroArray() by reference. The function zeroArray() accepts an Array object as a parameter
and sets all the elements of that array to 0. It can modify the array because the array is passed by
reference.
function zeroArray (theArray:Array):Void {
var i:Number;
for (i=0; i < theArray.length; i++) {
theArray[i] = 0;
}
}
var myArray:Array = new Array();
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
zeroArray(myArray);
trace(myArray); // 0,0,0