Skip navigation

JavaScript reference variable references only the final referred object, not a reference itself. When reading this first time, I got confused little.

Consider the JavaScript code below

// declare a variable
var aNames;
// create array and assign reference to aNames
aNames = Array("vkanakaraj", "rajakvk", "javascript");
// declare another variable and reference it to aNames
refNames = aNames;
// check its working
// now assign another array to aNames
aNames = Array(22,25,10);
// still points to vkanakaraj

got it?


  1. I think of it this way:

    Javascript variables always are object references (or null). Assignment is always a case of assigning a specific object.

    BTW, if you want a behavior like that, make aNames an object:

    var aNames;
    aNames = new Object;
    aNames.arr = Array(“vkanakaraj”, “rajakvk”, “javascript”);
    var refNames;
    refNames = aNames;
    aNames.arr = Array(22,25,10);
    // gives 22

  2. A couple of comments:

    If you are going to use the Array constructor, don’t forget to put the new keyword in front of it (ie aNames = new Array(“a”, “b”, “c”)).

    Almost everyone recommend using the array literal notation instead ( aNames = [“a”, “b”, “c”] )

    In fact in this context it highlights why the reference still points to the first object.. it is because you’ve created a new object by calling the constructor a second time. So your variable is a reference to that object instance (not a reference to the reference). This is only logical!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: