Javascript Functions

Passing Parameter Values to Functions

There are two ways JavaScript passes data to functions: by value and by reference. If data is passed by value, the function makes a copy of the data and works on the copy. The original data is not changed. If data is passed by reference, the function receives a reference to the memory location of the data and works on the data itself. The original data is changed. In Javascript, all primitive data types--strings, numbers, boolean--are passed by value. Aggregate types--objects, arrays--are passed by reference.

Passing by value

The following script sets a variable, num, to an integer value of 5. It is passed to a function that increments the value by 1. When the value of the variable is printed before, in, and after the function call, the value before and after the function is the same, but it was incremented in the function. Hence, the function had its own copy of the variable.

<script type="text/javascript">
<!--
// set value of variable
var num = 5;

function incrementNum(x)
{
  // ++ is an increment operator
  ++x;
  document.write("num in function is: " + x + "<br />");
}

//-->
</script>

<script type="text/javascript">
<!--
  document.write("num before function is: " + num + "<br />");
  incrementNum(num);
  document.write("num after function is: " + num + "<br />");
//-->
</script>

Result:

Passing by reference

The following script creates an object and set its property 'name' to a text string. The object is passed to a function where its property is changed. Printing it before, during, and after the function call shows that the string changes during the function call and remains changed when the function call returns. Hence, the function worked on the object itself and not on a copy.

<script type="text/javascript">
<!--

// create an object
var myObj = new Object();
// give object a property called "name" and
// assign a strong value to it
myObj.name = "I have a name";

function changeObjName(x)
{
  // x is a REFERENCE to myObj;
  // the object properties can be accessed and changed
  // through the reference
  x.name = "I had a name";
  document.write("object name in function is: " + x.name + "<br />");
}

//-->
</script>

<script type="text/javascript">
<!--
  document.write("object name before function is: " + myObj.name + "<br />");
  changeObjName(myObj);
  document.write("object name after function is: " + myObj.name + "<br />");
//-->
</script>

Result: