Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jul 2008
    Thanked 0 Times in 0 Posts

    Passing an Object by Reference

    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.

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Thanked 603 Times in 583 Posts
    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.
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts