TOPIC: Object References, Copying, and Garbage Collection
In JavaScript, primitive values like numbers and strings are copied by value. When you assign a primitive variable to another variable, you get an independent copy. Changing one has no effect on the other.
Objects behave completely differently. When you assign an object to a variable, the variable does not hold the object itself — it holds a reference to the object, which is a pointer to where the object lives in memory. Assigning that variable to a second variable copies the reference, not the object. Both variables now point to the same object in memory. Modifying the object through one variable will be visible through the other.
This has practical consequences. When you pass an object to a function, you are passing the reference. The function can modify the original object's properties. If this is not what you want, you need to create a copy explicitly.
Shallow copying can be done with Object.assign or the spread operator. Both approaches copy the top-level properties of an object into a new object. But if those top-level properties are themselves objects, only the references are copied — nested objects are still shared. For a fully independent copy at every level, you need a deep clone, achieved through structured cloning or a recursive copy function.
Garbage collection is the automatic process by which JavaScript reclaims memory that is no longer reachable. The engine tracks which objects are reachable from the program's roots — global variables, active function call stacks, and so on. Any object that can no longer be reached from any root is eligible for collection and its memory is freed. Developers rarely need to manage memory manually, but understanding reachability helps avoid memory leaks in long-lived applications.