4

Just a (hopefully) quick question to clear something up with how Javascript handles objects. I'm not used to JS so it came as a bit of a surprise, which is why I want to double check!

Say I have an object:

function food(price) {
  this.price = price || 100; 
}

var myFood = new food(100);

And then store this object in two arrays:

var foo = [];
var bar = [];
foo.push(myFood);
bar.push(myFood);

Am I right in thinking that all I'm doing here is storing a REFERENCE to myFood? I'm not creating a COPY of the object? So if I were to, say:

foo[0].price = 50;

Would bar[0].price ALSO == 50, as it stores a reference to myFood, and it is myFood that has actually had its price affected, not foo or bar?

Many thanks in advance! I've seen a few stack overflow threads that mention this issue as part of a wider post, but I just wanted to lay it all out there to make sure! Best regards

flukeflume
  • 707
  • 1
  • 6
  • 14
  • 3
    Why did you not just run the code to see? – Esailija Jun 20 '12 at 21:24
  • possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Gordon Gustafson Jun 20 '12 at 21:29
  • @Esailija - thanks for your comment! I did before I came to SO, but I thought I must have been missing something, somewhere, that was more complex than the plain and simple truth. :) – flukeflume Jun 20 '12 at 21:31
  • Hi Trinithis - that's fair enough, I just thought I was missing something! Sorry again. – flukeflume Jun 20 '12 at 21:38
  • Just to add comment that I found this entirely useful and quickly and concisely answered my reason for visiting SO on this occasion. The fact that the OP new what he was talking about meant the question was easy to understand, whilst also easy to find for someone who wasn't quite sure how to describe what he was looking for. ( I searched "multiple references to objects" =) – happilyUnStuck May 25 '13 at 14:10

2 Answers2

2

Yes, javascript will just push a reference not a copy of the object.

TheZ
  • 3,663
  • 19
  • 34
  • Fantastic! Thanks so much for your quick reply - I've just seen a wonderful future between myself and javascript opening before my eyes thanks to you! :D I'll accept as soon as it permits me. Thanks again! – flukeflume Jun 20 '12 at 21:30
2

You are correct. But it's incredibly easy to just do it and see what happens.

http://jsfiddle.net/67haQ/

You clearly seem to know how it works already, a little playing around for confirmation seems easier than a SO question.

Just sayin'

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • Hi Alex, thanks for this - I'm starting to feel a bit daft for coming to SO about it, like you say! I'll make sure to keep that in mind in the future. – flukeflume Jun 20 '12 at 21:33