When Primitives Behave Differently
You'll learn why primitives never cause the "shared state" problems that objects create, and see the contrast in action.
The Fundamental Difference in Action
By now you know that primitives are copied by value while objects are copied by reference. This difference produces dramatically different behaviors in identical-looking code.
When you pass a primitive to a function or assign it to another variable, JavaScript creates a completely independent copy. Changes to one copy never affect the other. With objects, you're passing around a reference (like a shared address), so changes appear everywhere.
Side-by-Side Contrast
// Primitive behavior
let x = 10;
let y = x; // y gets its own copy of 10
y = 20;
console.log(x); // 10 (unchanged!)
// Object behavior
let obj1 = { value: 10 };
let obj2 = obj1; // obj2 gets the same reference
obj2.value = 20;
console.log(obj1.value); // 20 (changed!)
The first example shows primitive independence: y changing has zero impact on x. The second shows reference sharing: mutating through obj2 affects obj1 because they point to the same object.
Why This Matters
Primitives are predictable and safe. You can pass numbers, strings, or booleans around freely without worrying about accidental modifications elsewhere in your code. Objects require more careful thinking—every time you pass one, you're granting access to the original data.
Think of primitives like photocopies: each variable gets its own independent sheet. Objects are like shared Google Docs: everyone editing the same document sees each other's changes.
Key Takeaway: Primitives behave differently from objects because they're always copied, never shared—making them immune to the unintended mutation problems that plague object references.