I'm confused as to how object references work in Javascript with regards to arrays and haven't found any relevant material for this specific question. I have the following code. I initialize an array called arr
of objects and set a new variable c
equal to the first element in the array. If I alter the array element, the variable c
is also changed as expected. Therefore I assume c is a pointer to the first element of the array.
However, If I set arr
to a new array entirely, the variable c
doesn't update. I would expect it to either A) Update to 'chameleon' which is the first element of the new array or, more likely, B) become undefined.
What object is the variable c
pointing to after the arr
is set equal to a new array? Does it become its own object?
var arr = [{animal: 'cat'}, {animal: 'bear'}];
var c = arr[0];
console.log(JSON.stringify(c.animal));
// Prints 'cat'
arr[0].animal = 'iguana';
console.log(JSON.stringify(c.animal));
// Prints 'iguana'
arr = [{animal: 'chameleon'}, {animal: 'bear'}];
console.log(JSON.stringify(c.animal));
// Prints 'iguana' instead of 'chameleon'