I am new to JavaScript and getting my hands on the spread operator. I understand that it will deep copy the top-level elements of an array or object but shallow copy the nested arrays or objects. I wanted to see it action and hence the code below but was unable to get the required output as per my understanding.
const originalObject = {
name: 'Alice',
address: {
street: '123 Main St',
city: 'Anytown',
},
};
const copiedObject = { ...originalObject };
console.log(copiedObject.name === originalObject.name); // Expected Output: false but Outputs: true
originalObject.address.city = 'Newtown';
console.log(copiedObject.address.city); // Output: "Newtown" (modification affects both objects)
console.log(originalObject.address.city);
console.log(copiedObject.address === originalObject.address); // Output: true (Can we understand this means both has a reference to the same object?)
Shouldn't it give an output as false? console.log(copiedObject.name === originalObject.name);
Could someone explain in simpler terms how can I visualise it in code and also compare if two properties share the same reference in javascript?
Similar questions on stackoverflow thay I went through but couldn't find an answer:
console.log(copiedObject === originalObject);?