In JavaScript, it appears if I define an array, print that array to the console, then change the array, then print to the console again, the two printings will appear different. Same for objects. This makes sense to me - the first time I print it, it hasn't changed yet, and the second time it has been changed.
However, through testing I've found that if I define an object within an array, print it, change the object, then print again, both printings will be the same (they will both be the changed version). Similarly if I define an array within an object, print it, change the array, then print it again, both printings will be the same (they will both be the changed version).
I think this may be related to passing by reference or by value? But I'm unclear how to relate that concept here. Some articles that I think may be related to my answer:
(SO) Is JavaScript a pass-by-reference or pass-by-value language?
(SO) Javascript by reference vs. by value
http://snook.ca/archives/javascript/javascript_pass
If anyone could help explain I would be very appreciative. Here are the tests I wrote to exemplify what discrepancy I'm asking about:
// Testing changing an array
// RESULT: Array console.logs are DIFFERENT before and after the change.
var arr123 = [1,2,3];
console.log(arr123);
arr123[0] = 4;
arr123[1] = 5;
arr123[2] = 6;
console.log(arr123);
// Testing changing an object
// RESULT: Object console.logs are DIFFERENT before and after the change.
var obj123 = {
first: 1,
second: 2,
third: 3
};
console.log(obj123);
obj123.first = 4;
obj123.second = 5;
obj123.third = 6;
console.log(obj123);
// Testing changing an object inside of an array.
// RESULT: Array console.logs are THE SAME before and after the change, reflecting the change.
var arrOfAnObj = [
{first: 1, second: 2, third: 3}
];
console.log(arrOfAnObj);
arrOfAnObj[0].first = 4;
arrOfAnObj[0].second = 5;
arrOfAnObj[0].third = 6;
console.log(arrOfAnObj);
// Testing changing an array inside of an object.
// RESULT: Object console.logs are THE SAME before and after the change, reflecting the change.
var objOfAnArr = {
arr: [1, 2, 3]
};
console.log(objOfAnArr);
objOfAnArr.arr[0] = 4;
objOfAnArr.arr[1] = 5;
objOfAnArr.arr[2] = 6;
console.log(objOfAnArr);