0

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"
LeLo
  • 29
  • 2
  • 1
    Assigning an object reference from one variable to another does **not** make a copy. You're just working with references. Strings and numbers are not objects. – Pointy Aug 18 '15 at 16:14
  • 3
    You are not making a copy of anything, you are assigning `obj2` the exact same object as `obj1` references. Do some research on "cloning", or more specifically "deep clone" – musefan Aug 18 '15 at 16:14

0 Answers0