Because its the same reference
(same address for memory location where the object is stored) both x and y are now the same reference so changing one will change the value stored, and now as they are the same reference they will output the same object values.
I would add something extra to make this answer more productive.
Shallow -Copy
Shallow copy is a bit-wise copy of an object. A new object is created
that has an exact copy of the values in the original object. If any of
the fields of the object are references to other objects, just the
reference addresses are copied i.e., only the memory address is
copied.
example
let x={"a":1,"b":2};
let y=x; //It makes a copy of the reference to x into y
So, the addresses of x and y will be the same i.e. they will be pointing to the same memory location.
so if you do this
y.a=9;
and now when you print y on the screen
console.log(y) // it prints {"a":9,"b":2};
but the interesting fact here is , when you print x
console.log(x) // it also prints {"a":9,"b":2};
So Now how to change this scenario??. The solution is a deep copy
Deep copy
A deep copy copies all fields and makes copies of dynamically
allocated memory pointed to by the fields. A deep copy occurs when an
object is copied along with the objects to which it refers.
in Lehman terms you create a variable y allocate it a different memory location, copy all the members of x, assign the copied members to y
the easiest way to do it is by stringifying
the object
let y=JSON.parse(JSON.stringify(x))
now if we do
y.a=9
and print y
console.log(y) // it prints {"a":9,"b":2};
and if we print x
console.log(x) // it prints {"a":1,"b":2};
/// shallow copy
let x = {
"a": 1,
"b": 2
};
let y = x;
y.a = 9;
console.log(y);
console.log(x);
// Deep Copy
let z = {
"a": 1,
"b": 2
};
let t = JSON.parse(JSON.stringify(z));
t.a = 9;
console.log("z:", z);
console.log("t:", t);
This scenario becomes more fun when we have nested objects
let c = {
"a": {
"A": 1
},
"b": {
"B": 2
}
};
let t = Object.assign({}, c); // It is also shallow copying
t.a.A = "7"; // since a is a nested object so again reference is passed
console.log(c);
console.log(t)
console.log("Second Scenario-------------------")
let d = {
"a": {
"A": 1
},
"b": {
"B": 2
}
};
let k = JSON.parse(JSON.stringify(d));
k.a.A = 88
console.log(d)
console.log(k)