1

I wonder how it happens !

I have a json array containing one value. I assign it to a VAR obj named 'first'. Then I assign first's value to other VAR obj called 'second'. Then, I push another json value stored in 'third' into 'second' obj with push() fun. According to my knowledge, 'first' obj should have 'Hello 1' value & 'second' obj should have ('Hello 1' & 'Hello 2' values. But when I check my console log of browser, I can see both values ('Hello 1', 'hello 2') or two objects injected into both VAR objects 'first' & 'second'.

function jsonarray()
{
 var first=[{name:"Hello 1"}]

 var second=first;

 var third=[{name:"Hello 2"}]

 second.push(third);

 console.log(third);
 console.log(second);
 console.log(first);   
}

I don't know if something is wrong or out of my knowledge. Please update me with appropriate explanation.

js fiddle: http://jsfiddle.net/micronyks/eLLZw/

micronyks
  • 54,797
  • 15
  • 112
  • 146

1 Answers1

2

When you assign first value to second var, you assing the REFERENCE, so both variables point to the same object. If you want differents objects for every variable, you need to do a copy
Have a look at this answer: https://stackoverflow.com/a/7486130/2873381

Community
  • 1
  • 1
xecgr
  • 5,095
  • 3
  • 19
  • 28