CKTIS / JavaScript
Memory: object sharing and copies
Assigning an object does not copy it. Learn the difference between an alias, a shallow copy, and copying a selected branch, and why const does not prevent property mutations.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
const alias = original;
const shallow = { ...original };
const copiedBranch = { ...original, nested: { ...original.nested } };JavaScript does not give objects exclusive owners. Assignment and argument passing pass a value; for an object, they preserve its identity rather than copying its properties. Several variables can therefore refer to the same object. Mutation is visible through every such alias, but assigning a different object to one variable does not change the others. Primitive values are immutable.
const prevents reassignment of a variable, not mutation of its object. const alias = original makes no copy. In contrast, { ...original } creates a new object and copies the values of own enumerable properties, including Symbol-keyed properties. This is a shallow copy: nested objects remain shared. Spread reads values, can invoke getters, and does not preserve the source's prototype or property descriptors.
To change nested independently in this example, copy that branch too: { ...original, nested: { ...original.nested } }. This is not a general deep-copy algorithm: objects nested further inside would still be shared. At interface boundaries, establish whether a function may mutate an incoming object or must create an independent copy of the data it needs.
Memory reclamation is automatic, but no particular collection time should be assumed. Removing one reference does not free an object if it remains reachable through another path. This example demonstrates value and identity semantics, not a physical stack-versus-heap layout. It uses ES2018 object spread syntax and requires no Web APIs.
Examples
const original = { score: 1, nested: { count: 1 } };
const alias = original;
const shallow = { ...original };
const copiedBranch = { ...original, nested: { ...original.nested } };
alias.score = 2;
shallow.nested.count = 3;
copiedBranch.nested.count = 4;
console.log(alias === original);
console.log(shallow === original);
console.log(original.score, shallow.score);
console.log(original.nested.count, copiedBranch.nested.count);Result
true false 2 1 3 4
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.