Introduction
Understanding how new objects and variable assignments work helps you avoid bugs when changing data.
const obj1 = { key: 'value' }; const obj2 = obj1; // obj2 points to the same object const obj3 = { key: 'value' }; // fresh new object
const a = { name: 'Alice' }; const b = a; b.name = 'Bob'; console.log(a.name);
const a = { name: 'Alice' }; const b = { name: 'Alice' }; b.name = 'Bob'; console.log(a.name);
const a = { count: 1 }; const b = a; const c = { count: 1 }; console.log(a === b); console.log(a === c);
const original = { score: 10 }; const copy = original; const fresh = { score: 10 }; copy.score = 20; console.log('original.score:', original.score); console.log('fresh.score:', fresh.score); console.log('original === copy:', original === copy); console.log('original === fresh:', original === fresh);
let b = a;?{} creates a new, fresh object literal.Object.assign({}) needs a source object to copy from; let obj = obj2; copies reference; let obj = new Object(obj2); creates an object but with a reference or unexpected behavior.let a = { x: 1 };
let b = a;
b.x = 5;
console.log(a.x);b points to the same object as a.bb.x to 5 changes the shared object property.a.xa and b reference the same object, a.x is now 5.let obj1 = { val: 10 };
let obj2 = obj1;
obj2 = { val: 20 };
console.log(obj1.val);const obj1 = { a: 1 };
const obj2 = ???
obj2.a = 5;
console.log(obj1.a);{ ...obj1 } creates a fresh object with copied properties.obj2.a does not affect obj1.a.Pass the test and this pattern moves unknown