2

I do not get stumped often but I am just at a loss of words right now.

Using Chrome 37.0.2062.120 m

Can someone explain to me why my console.log(); is reporting these results?

JS code

var some_obj = {min:1};

var another_obj = {};

console.log(some_obj);

another_obj['sometarget'] = some_obj; // <- What is this sorcery?!?!?
another_obj['sometarget']['required'] = true;

console.log(some_obj);

console.log() output

Object {min: 1}
Object {min: 1, required: true}

JSFIDDLE

http://jsfiddle.net/qrnaw7j2/1/

MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
  • What part of that result do you not expect? What's the surprise that has you stumped? – Alex Wayne Sep 23 '14 at 19:23
  • Searching would have found you a few hundred duplicates, here's one -> **http://stackoverflow.com/questions/9437981/object-pass-by-reference** – adeneo Sep 23 '14 at 19:28

1 Answers1

6

Objects in javascript are shared via reference.

So some_obj and another_obj['sometarget'] point to the same place in memory.

When you set ['required'] = true; in any of them, they will both get updated.

Luan Nico
  • 5,376
  • 2
  • 30
  • 60
  • Objects in javascript are not passed by reference ! – adeneo Sep 23 '14 at 19:28
  • The pointers to objects are not, but the objects per se are, because they share the same place in memory - they actualy 'point' to the same object. So I guess it depends on the notation :) – Luan Nico Sep 23 '14 at 19:33
  • 1
    It's generally referred to as "copy of a reference" or "reference-like", javascript doesn't have pointers, nor does it pass by true reference. – adeneo Sep 23 '14 at 21:32
  • 1
    Thanks Luan Nico! @adeneo The answer was explained in plain English and while there is argument over proper terminology of pass-by-whatever, Luan's `So some_obj and another_obj['sometarget'] point to the same place in memory.` remark is self-explanatory. – MonkeyZeus Sep 24 '14 at 03:19