1

I wrote a normal code for deep copying an object and then printing both the original object as well as the copy object, before and after making some changes to the copy object.

This is to show that the change has not affected the original object, and that both the objects are independent of each other.

The problem is that the copy object shows the deep changed property even before the change was made.

One answer might be that somehow it's using some old values, since I tested this code on the Google Chrome browser. (I did the test many times to figure out the reason of it's behavior.) However that doesn't seem possible as I'm declaring them again and assigning new values each time the code executes.


The code:

function deepCopy(obj) {
    let tempObj = {};

    for(let key in obj) {
        if(typeof obj[key] == "object") {
            tempObj[key] = deepCopy(obj[key]);
        }
        else {
            tempObj[key] = obj[key];
        }        
    }

    return tempObj;
}

let user = {
    name: "goku",
    age: 18,
    info: {
        powerLevel: 10000,
        race: "saiyan",
    },
};

let copyUser = deepCopy(user);

console.log("Before changing");
console.log(user);
console.log(copyUser);

copyUser.info.powerLevel = 50;

console.log("After changing");
console.log(user);
console.log(copyUser);

The output of the code should be like this:

Before changing (Of original object) powerLevel: 10000 (Of copy object) powerLevel: 10000

After changing (Of original object) powerLevel: 10000 (Of copy object) powerLevel: 50

proxyConsoleLog.js:12 Before changing
proxyConsoleLog.js:12 {name: "goku", age: 18, info: {…}}age: 18info: {powerLevel: 10000, race: "saiyan"}name: "goku"__proto__: Object
proxyConsoleLog.js:12 {name: "goku", age: 18, info: {…}}age: 18info: {powerLevel: 50, race: "saiyan"}name: "goku"__proto__: Object
proxyConsoleLog.js:12 After changing
proxyConsoleLog.js:12 {name: "goku", age: 18, info: {…}}age: 18info: {powerLevel: 10000, race: "saiyan"}name: "goku"__proto__: Object
proxyConsoleLog.js:12 {name: "goku", age: 18, info: {…}}age: 18info: {powerLevel: 50, race: "saiyan"}name: "goku"__proto__: Object
undefined

Why does the value of powerLevel in the copy object changes before the change was actually made?

Chinmay Ghule
  • 91
  • 1
  • 6
  • 3
    console is not always accurate with logging. JSON.stringify it and see that is is not the issue you think it is. – epascarello May 14 '21 at 17:06
  • 1
    Another one https://stackoverflow.com/questions/11284663/console-log-shows-the-changed-value-of-a-variable-before-the-value-actually-ch – ponury-kostek May 14 '21 at 17:11

1 Answers1

1

The console lazy loads objects. The blue square icon in the chrome console is a sign telling you that this happens.

var obj = { foo: { bar : 1 } };
console.log(obj);
console.log(JSON.stringify(obj));
obj.foo.bar = 2;
console.log(obj);
console.log(JSON.stringify(obj));
epascarello
  • 204,599
  • 20
  • 195
  • 236