Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
122
rated 0 times [  126] [ 4]  / answers: 1 / hits: 15297  / 9 Years ago, wed, may 27, 2015, 12:00:00

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?


More From » arrays

 Answers
96

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).


[#66440] Tuesday, May 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sergiobrayanc

Total Points: 162
Total Questions: 97
Total Answers: 94

Location: Lesotho
Member since Wed, Jun 2, 2021
3 Years ago
;