Why did the "copy" change?
Why const b = a doesn't copy an object, and how to make a real copy.
const passport = { name: "Byte", age: 3 };
const archive = passport;
archive.age = 4;
console.log(passport.age);Numbers and strings are stored in the variable themselves. But an object (and an array) lives separately in memory, and the variable holds only a reference to it — like a house's address.
const archive = passport copies the address, not the house. Now two variables point at one and the same object, and a change through one shows through the other.
const a = { x: 1 };
const b = a;
const c = { x: 1 };
console.log(a === b);
console.log(a === c);=== on objects compares references: "is it the same object", not "is the content the same".Why this way? Objects can be huge — thousands of properties, nested arrays. If every assignment or function call copied them whole, programs would be slow and eat memory. Passing an address is instant.
A real copy is made explicitly — with spread: { ...passport } creates a new object with the same properties.
const passport = { name: "Byte", age: 3 };
const archive = { ...passport };
archive.age = 4;
console.log(passport.age);
console.log(archive.age);{ ...obj }). And const b = a isn't a copy; it's a second label on the same folder.Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.