0

I think my question already answered but i could not find the answer that would satisfy me.

Problem is that;

The code print "3" but i dont understand how can it be because firstly person assigned list[0] then i implement person.ID so which speciality of javascript does provide this.Can you explain me

var person = {};
person.name = "John";
person.surname = "Connor";
var list = [];
list [0] = person; //In here i did not generate ID 
person.ID = 3;
console.log(list[0].ID);
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
JohnConnor
  • 33
  • 1
  • 1
  • 11

1 Answers1

0

The statement list [0] = person; loads the object reference (person) in to first index of Array.

So any modification to object, also updates Object inside list and vice-versa. because objects are passed as references not as values.

that is why after this person.ID = 3; console of first index also print 3.

If you want to avoid this you could make a copy of object before pushing in to Array.

To Copy you could use Object.assign({},person) which makes a shallow copy of object

Now following code does not print 3.

var person = {};
person.name = "John";
person.surname = "Connor";
var list = [];
list [0] = Object.assign({},person); //In here i did not generate ID
person.ID = 3;
console.log(list[0].ID);
ngChaitanya
  • 435
  • 2
  • 8