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?