contents   index   previous   next

Passing information to functions


JavaScript uses different methods to pass variables to functions, depending on the type of variable being passed. Such distinctions ensure that information gets to functions in the most complete and logical ways. To be technically correct, the data that is passed to a function are called arguments, and the variables in a function definition that receive the data are called parameters.


Primitive types, namely, strings, numbers, and booleans, are passed by value. The value of theses variables are passed to a function. If a function changes one of these variables, the changes will not be visible outside of the function where the change took place.


Composite types, objects and arrays, are passed by reference. Instead of passing the value of the object, that is, the values of each property, a reference to the object is passed. The reference indicates where in a computer's memory that values of an object's properties are stored. If you make a change in a property of an object passed by reference, that change will be reflected throughout in the calling routine.


In ScriptEase it is possible to pass primitive types by reference instead of by value, which is the default. When a function is defined, an ampersand, &, may be put in front of one or more of its parameters. Thus, when the function is called, an argument, corresponding to a parameter with an ampersand, is passed by reference instead of by value. The following fragment illustrates.


var num1 = 4;

var num2 = 4;

var num3;

SetNumbers(num1, num2, num3, 6)


function SetNumbers(&n1, n2, &n3, &n4)


   n1 = n2 = n3 = n4 = 5;



After executing this code, the values of variables is:


num1 == 5

num2 == 4

num3 == 5


The variable num1 was passed by reference to parameter n1. When n1 was set to 5, num1 was actually set to 5 since n1 merely pointed to num1. The variable num2 was passed by value to parameter n2. When n2, which received an actual value of 4, was set to 5, num2 remained unchanged. The variable num3 was undefined when passed by reference to parameter n3. When n3, which pointed to num3, was set to 5, num3 was actually set to 5 and defined as an integer type. The literal value 6 was passed to parameter n4, but not by reference since 6 is not a variable that can be changed. Though n4 has an ampersand, the literal value 6 was passed by value to n4 which, in this example, becomes merely a local variable for the function SetNumbers().


Simulated named parameters