Memory and References
Understand how memory works in programming: stack vs. heap, value vs. reference, and why it causes subtle bugs.
What you'll learn
- How programs use memory to store data
- The difference between stack and heap memory
- Value types vs. reference types and why it matters
- How copying and comparison behave differently for each
- Common bugs caused by unexpected reference sharing
Concept
Memory and References
Every variable in your program lives in memory — the computer's workspace for data. Understanding how memory is organized, and the difference between value types and reference types, explains some of the most confusing bugs beginners encounter. This is the lesson where "why did changing this variable also change that one?" finally makes sense.
Stack and Heap
Memory is divided into two regions:
- The stack — fast, automatically managed, used for primitive values and function call frames. When you declare
const x = 42, the value42goes on the stack. When a function returns, its stack frame is cleaned up automatically. - The heap — slower, manually or garbage-collector managed, used for objects and arrays. When you declare
const obj = { name: "Ada" }, the object itself lives on the heap, and the variableobjon the stack holds a reference (a pointer) to that heap location.
Value Types (Primitives)
Primitives (string, number, boolean, null, undefined) are value types. When you assign a primitive to a new variable, the *value* is copied:
let a = 5;
let b = a; // b gets a copy of the value 5
b = 10; // changing b does not affect a
console.log(a); // 5 (unchanged)
Each variable is independent. This is intuitive and safe — modifying one never affects the other.
Reference Types (Objects and Arrays)
Objects and arrays are reference types. When you assign an object to a new variable, the *reference* is copied, not the object itself. Both variables now point to the same object in memory:
const original = { count: 1 };
const copy = original; // copy references the SAME object
copy.count = 99; // modifying through copy...
console.log(original.count); // 99 — original is also changed!
This is the #1 surprise for beginners. copy is not a copy of the object — it is a second label for the same object. Modifying through either variable affects both, because there is only one object.
Copying Objects
To create an actual copy of an object, you must explicitly copy its properties:
// Shallow copy (one level deep):
const shallow = { ...original }; // spread syntax
const arrCopy = [...array]; // array spread
// Deep copy (all levels) — for nested structures:
const deep = JSON.parse(JSON.stringify(original));
A shallow copy duplicates the top level but nested objects are still shared. A deep copy duplicates everything. Choose based on your data structure.
Comparison Behavior
Value and reference types also differ in comparison:
// Primitives compare by value:
console.log(5 === 5); // true
console.log("hi" === "hi"); // true
// Objects compare by reference (identity):
console.log({} === {}); // false — different objects
const obj = {};
console.log(obj === obj); // true — same reference
Two objects with identical contents are not equal with === because they are different objects in memory. Equality checks identity, not structural equality.
Why This Matters
Reference sharing causes real bugs: you modify a function parameter expecting it to be a local copy, but it is the caller's original object. You push to an array that is shared between two components, and both update unexpectedly. The defense is awareness: always know whether you are working with a value or a reference, and copy explicitly when you need independence.
Example
// --- Value type: independent copies ---
let scoreA = 100;
let scoreB = scoreA; // value copied
scoreB += 50;
console.log(scoreA, scoreB); // 100 150 — independent
// --- Reference type: shared object ---
const playerA = { name: "Ada", score: 100 };
const playerB = playerA; // reference copied, NOT the object
playerB.score += 50;
console.log(playerA.score); // 150 — playerA also changed!
// --- Fix: create a real copy ---
const playerC = { ...playerA }; // shallow copy (new object)
playerC.score += 50;
console.log(playerA.score); // 150 — playerA is safe now
console.log(playerC.score); // 200
// --- Nested objects need deep copy ---
const config = { db: { host: "localhost", port: 5432 } };
const configCopy = { ...config }; // shallow — db is still shared!
configCopy.db.port = 3306;
console.log(config.db.port); // 3306 — still shared!
const deepCopy = JSON.parse(JSON.stringify(config));
deepCopy.db.port = 1234;
console.log(config.db.port); // 3306 — now independent
// --- Array reference sharing ---
const original = [1, 2, 3];
const ref = original;
ref.push(4);
console.log(original); // [1, 2, 3, 4] — original changed!
const realCopy = [...original];
realCopy.push(5);
console.log(original); // [1, 2, 3, 4] — original is safe
This example demonstrates value independence, reference sharing, shallow vs. deep copy, and array reference bugs. Each section shows the problem and the fix — the pattern you will encounter repeatedly in real code.
Try it
- JSON Formatter
JSON serialization (used by the formatter) creates a deep copy of data. Paste nested objects and see how the structure is preserved.
- JSON Diff
Diffing objects by value (not reference) is what this tool does. Two objects with the same content show no diff, even though {} === {} is false.
Common mistakes
The mistake
Assigning an object to a new variable and expecting an independent copy.
The fix
Use spread syntax { ...obj } for a shallow copy, or JSON.parse(JSON.stringify(obj)) for a deep copy. Never assume assignment copies an object — it only copies the reference.
The mistake
Using === to compare two objects with the same contents and expecting true.
The fix
=== compares references, not contents. For deep equality, use a library function (like lodash.isEqual) or compare specific properties. JSON.stringify(a) === JSON.stringify(b) works for simple cases but is fragile.
The mistake
Mutating an object passed as a function parameter, surprising the caller.
The fix
If a function should not modify its input, work on a copy: const local = { ...input }. Or use immutable patterns — return a new object instead of modifying the input. This makes the function's behavior predictable.
Related Resources
Related Cheatsheets
- JavaScript Cheatsheet
Reference for spread syntax, destructuring, and object copying patterns.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.