View Full Version : Passing an Object by Reference

07-29-2008, 11:59 PM
I noticed the other day that I do not have to pass an Array to a Function in order for that Function to access the content of the Array.

From what I have learnt (and its not very much so far!) if you wish to use a value that exists outside a Function within that Function then you need to pass that value into the Function, either by value or by reference, as follows;

var x = 1;

Function myfunction(a)
a += a;


The above example is obviously passing by value, but you would think the same 'rules' would apply to an object such as an Array; it has to be passed to the Function before you can use its contents.

I was messing with some scripts that involved two separate Functions and I wanted to pass an Array between the two. I could not call one Function from the other as both were unrelated and were triggered by separate events. To do this I declared the Array outside of both Functions and then referred to the Array within the Functions without passing by reference, or at least without placing a variable within the brackets of my Function. And it worked! Example;

var x = new Array();

Function one()

Function two()

Any idea why I did not have to pass the Array into the function at all? Clearly my second example shows this works, but my main concern is that it is not the "correct" way of doing it. This seems to contradict what I have been learning.

Thanks for your time.

rnd me
07-30-2008, 12:13 PM
if the variable is in the scope outside the two functions, either global or in that of a parent function, the variable can be referred to but all subsequent lower scopes.

you examples create a global, which can be reached anywhere.

arrays are objects, and like all objects are passed by references. primitives are asses at time of calling and are thus passed as values.