In this code, I assign a copy of array1 to a variable array2, but when I change array1, it changes array2. Why does this happen??
var array1 = [1, 2, 3, 4, 5];
var array2 = array1;
array1.pop();
console.log("array1: " + array1 + "\narray2: " + array2);
//output: array1: 1,2,3,4
// array2: 1,2,3,4
Since arrays are objects, I tested the same concept with an object and got the same result. I deleted a property from the original object and it deleted the same property from the copy of the other object. What is going on under the hood?
var obj1 = {name: "object", day: "Tuesday", color: "yellow"};
var obj2 = obj1;
console.log("BEFORE DELETE:");
console.log("obj1 properties:");
for(var prop in obj1) {
console.log(prop);
}
console.log("obj2 properties:");
for(var prop in obj2) {
console.log(prop);
}
delete obj1.color; //delete only from obj1
console.log("AFTER DELETE:");
console.log("obj1 properties:");
for(var prop in obj1) {
console.log(prop);
}
console.log("obj2 properties:");
for(var prop in obj2) {
console.log(prop);
}
//output: BEFORE DELETE:
// obj1 properties:
// name
// day
// color
// obj2 properties:
// name
// day
// color
// AFTER DELETE:
// obj1 properties:
// name
// day
// obj2 properties:
// name
// day
It's confusing, because I would expect it to behave the same as this:
var cow = "moo";
var calf = cow;
console.log("BEFORE CHANGE:");
console.log("cow: " + cow); //prints "moo"
console.log("calf: " + calf); //prints "moo"
cow = "oink";
console.log("AFTER CHANGE:");
console.log("cow: " + cow); //prints "oink"
console.log("calf: " + calf); //still prints "moo"