Search code examples
javascriptarraysjavascript-objects

In an array of named objects in javascript - are the names accessible?


If we create some objects, and fill an array with those objects, are the names stored within the array, or only the properties of the object? I guess this may be trivial, but I haven't been able to find an answer.

var boxA = {color: "red", width: 100};
var boxB = {color: "yellow", width: 200};
var boxC = {color: "blue", width: 300};

boxArray = [boxA, boxB, boxC];

for (var i = 0; i < boxArray.length; i++) {

    //****
    // What code do we insert here to log
    // boxA
    // boxB
    // boxC
    //****

}

Of course, it is a trivial workaround to add

boxA.box = boxA; 

etc and then call

console.log(boxArray[i].box);

But is that really necessary?


Solution

  • No, that does not work like that.

    The variable name is a reference to an object in a heap area of memory managed by JS automatically for you.

    In details it means that:

    var boxA = {color: "red", width: 100};
    

    this statement:

    1. Creates an object in the heap
    2. Associates a local symbol boxA with that object.

    So the object is referenced by one variable yet.

    var boxArray = [boxA];
    

    here:

    1. An array with one element is created. That element contains a reference to an object. A copy of the reference to be precise. So, the same original object is referenced twice now.
    2. A boxArray is assigned a reference to the array, which is also placed in the heap.

    To summarize: the variable names exist only in code listing for developers to easier reason about some objects in memory, instead of operating with memory addresses (which would be horrible).