Understand memory reference pointers vs deep cloning to prevent unintended state mutations in nested object graphs.
Learn how variables act as labeled containers for data using const, let, and var to manage lexical scope and reassignment safely in modern applications.
In JavaScript, primitives copy by value, but objects and arrays copy by reference.
Assigning an object to a new variable (const b = a) creates a shared reference pointer. Modifying a property on b silently mutates a!
{ ...obj } or Object.assign()): Copies top-level properties. Nested objects still share references in memory!structuredClone(obj)): Creates a completely independent clone of the entire object graph, including all nested objects and arrays.const original = {
name: "App",
settings: { theme: "dark" },
};
// Shallow Copy Problem
const shallow = { ...original };
shallow.settings.theme = "light";
console.log(original.settings.theme); // "light" (Mutated original settings!)
// Native Deep Clone (Modern ES2022 Standard)
const deepCopy = structuredClone(original);
deepCopy.settings.theme = "blue";
console.log(original.settings.theme); // "light" (Original untouched!)
[ Shallow Copy ] -> copy.settings ---+
+--> Shares same nested memory cell!
[ Original ] -> orig.settings ---+
[ Deep Clone ] -> clone.settings ----> Independent new memory cell!
JSON.parse(JSON.stringify(obj)): The old JSON deep copy trick loses Functions, undefined, Date objects, Set, Map, and crashes on circular references. Always use native structuredClone().Use structuredClone() for safe deep cloning. Next, let's explore modern native array grouping with Object.groupBy()!