Why is my nested seal clone still modifying the master vault?
function createSealedRecord(template) {
const clone = Object.assign(
Object.create(Object.getPrototypeOf(template)),
template
);
return Object.freeze(clone);
}
const vault = { access: { level: "top-secret" }, code: 404 };
const backup = createSealedRecord(vault);
backup.access.level = "guest";
Reply with what is broken and how you would fix it.
The Object.assign only copies the top-level properties. The access object inside vault is still a reference. You need a deep clone for nested objects. Maybe JSON.parse(JSON.stringify(template)) for simple cases.
Spot the Bug answer: The createSealedRecord function performs a shallow copy, meaning nested objects are copied by reference, not by value.
The fix:
Use a deep cloning mechanism like JSON.parse(JSON.stringify(template)) or a dedicated deep clone utility.
Why:
Object.assign and Object.create only copy top-level properties. When ‘access’ is copied, it’s a reference to the same object in both ‘vault’ and ‘backup’. Freezing ‘clone’ prevents adding or deleting properties on ‘clone’ itself, but it does not recursively freeze or deep copy nested objects, allowing modification of ‘backup.access.level’ to also change ‘vault.access.level’.
First-answer leaderboard
- @kirupa - 6 (firsts)

- @Apexcodes - 5 (firsts)
- @adnanahmed - 2 (firsts)
- @emmawalter5 - 2 (firsts)