let user = {
name: "John",
age: 30,
address: {
country: "England",
city: "Manchester"
}
}
let newUser = user; // shallow copy
newUser = newUser.address; // I assigned the nested object to newUser variable. (what happened in this place? Did I create a new object in memory? but if I make this(newUser = {country:"testing", city: "xxx"}), it will create a new object in memory. What is the differences between them?)
newUser.city = "London" // I change city of newUser, but this affects User object. Why And How affect User object?
console.log("newUser", newUser);
console.log("user", user);
Asked
Active
Viewed 301 times
0
-
2`let newUser = user;` does **not** make a shallow copy. After that declaration, both variables will refer to the same (single) object. – Pointy Aug 08 '22 at 19:07
-
1`newUser = Object.assign( {}, user.address )` – Deepak Kamat Aug 08 '22 at 19:08
-
This might help: https://stackoverflow.com/questions/12690107/clone-object-without-reference-javascript – Xyndra Aug 08 '22 at 19:10