1

Sorry if this has been asked before, but I need a much more straightforward answer than some of the complex examples I've found in my search...

If I create several global objects, let's say they're named Johnson, Smith, etc, and afterwards I push them to a global array called people, like people[0] = Johnson, people[1] = Smith...

Have I simply created a reference to that global object, or some sort of duplicate within the array?

So if I choose to add a new property to every object by iterating over the array, people[i].newProperty, am I just adding a new property to the original global object, or to the global object and the object within the array?

Secondly, would there be any sort of performance hit when assigning properties through the array versus creating the global objects inside of a single global object at the very beginning, like People.Johnson? I'm guessing there's no difference, but thought I would throw it out there.

Thanks!

LubosB
  • 195
  • 1
  • 10
  • 1
    As far as I know, inside the array will be 'references' to the original global objects you created, unless those are primitives like strings/numbers instead of 'object objects'. There's a small performance hit if you assign new properties to an object, since it'll have to reform its own internal structure. Better would be to already assign the newProperty to each object with a null value when you create them and just update that newProperty instead. The performance hit is very tiny though on modern machines. – Shilly Jul 01 '15 at 14:03

1 Answers1

2

Answering your questions:

Q: Have I simply created a reference to that global object, or some sort of duplicate within the array?

A: You created a reference indeed.

Q: So if I choose to add a new property to every object by iterating over the array, 'people[i].newProperty', am I just adding a new property to the original global object, or to the global object and the object within the array?

A: You are modifying the object and the one within the array, since they are the same.

Q: Secondly, would there be any sort of performance hit when assigning properties through the array versus creating the global objects inside of a single global object at the very beginning, like 'People.Johnson'? I'm guessing there's no difference, but thought I would throw it out there.

A: No, there is no performance difference.

Here are some great references for you to study and understand better this subject of objects in arrays for javascript:

[1] Changing array in JavaScript function changes array outside of function?

[2] is it possible to change values of the array when doing foreach in javascript?

[3] http://orizens.com/wp/topics/javascript-arrays-passing-by-reference-or-by-value/

[4] http://www.hunlock.com/blogs/Mastering_Javascript_Arrays

Community
  • 1
  • 1
EduardoFernandes
  • 3,091
  • 1
  • 13
  • 12