Arrays as Parameters



The following program demonstrates passing an array and passing array elements to a procedure.

function demo4()
{
var array1 = [1, 2, 3, 4, 5];
var outputString = "Effects of Passing an Entire Array By Reference: " + "\n" +
"\n" + "The values of the original array are: " + "\n";

// display original elements of array1
for (var ctr = 0; ctr < array1.length; ctr++)
{
outputString += " " + array1[ctr];
}

modifyArray(array1);

outputString += "\n" + "The values of the modified array are: " + "\n";

// display modified elements of array1
for (var ctr = 0; ctr < array1.length; ctr++)
{
outputString += " " + array1[ctr];
}

//---------------------------------------------------------------

outputString += "\n"+ "\n"+ "Effects of Passing an Entire Array By Value (using
slice): " + "\n" + "\n" + "The values of the original array are: " +
"\n";

// display original elements of array1
for (var ctr = 0; ctr < array1.length; ctr++)
{
outputString += " " + array1[ctr];
}

modifyArray(array1.slice());

outputString += "\n" + "The values of the modified array are: " + "\n";

// display modified elements of array1
for (var ctr = 0; ctr < array1.length; ctr++)
{
outputString += " " + array1[ctr];
}

//---------------------------------------------------------------

outputString += "\n"+ "\n"+ "Effects of Passing Array Element By Value:" +
"\n"+ "\n" + "array1[3] before modifyElementByVal: " + array1[3]

// array element passed by value
outputString = modifyElementByVal(array1[3], outputString)

outputString += "\n" + "array1[3] after modifyElementByVal: " + array1[3];

//---------------------------------------------------------------

alert(outputString);
}

// modifies the array it receives
function modifyArray(arrayParameter)
{
for (var sCtr = 0; sCtr < arrayParameter.length; sCtr++)
{
arrayParameter[sCtr] *= 2;
}
}

// modifies integer passed to it, but original is not modified
function modifyElementByVal(element, outputString)
{
outputString += "\n"+ "Value received in modifyElementByVal: " + element;
element *= 2;
outputString += "\n" + "Value calculated in modifyElementByVal: " + element;
return outputString;
}

results

The procedure call modifyArray(array1) passes a reference to array1 to modifyArray, where array1's elements are then multiplied by 2.

The procedure call modifyArray(array1.slice()) passes a copy of array1 to modifyArray, where the copy's elements are then multiplied by 2.

The call modifyElementByVal(array1(3), outputString) passes array element 3 to modifyElementByVal by-value where a copy of the element is multiplied by 2, but the result is lost when the procedure terminates because it was working with a copy.

Demos (click Array Test 4)