Primitive vs Reference Types
Understand how JavaScript handles primitives and objects — crucial for avoiding bugs when passing data between components.
Primitive vs Reference Types
Before diving deeper into component communication, you need to understand how JavaScript handles primitive types (strings, numbers, booleans) versus reference types (objects, arrays). This distinction matters greatly when passing props between components.
Primitive Types
let a = 10;
let b = a; // b gets a COPY of a's value
b = 20;
console.log(a); // 10 — unchanged!
console.log(b); // 20
Primitives are copied by value. Changing b does not affect a.
Reference Types
let objA = { name: 'Ryu', rank: 5 };
let objB = objA; // objB gets a REFERENCE to the same object
objB.rank = 10;
console.log(objA.rank); // 10 — changed!
console.log(objB.rank); // 10
Objects and arrays are copied by reference. Both variables point to the same object in memory. Changing one changes the other.
Why This Matters for Vue Props
| Prop Type | Parent → Child | Mutating in Child |
|---|---|---|
| Primitive (String, Number) | Copied by value | Only changes locally — parent unaffected |
| Reference (Object, Array) | Shared reference | Changes affect the parent too! |
If you pass an object as a prop and the child modifies it, the parent's data changes too — because they reference the same object. This can cause hard-to-track bugs. Always treat props as read-only and use events to communicate changes upward.
Key Takeaways
- Primitives are copied by value — changes to the copy do not affect the original
- Objects and arrays are copied by reference — changes affect both variables
- When passing objects/arrays as props, mutations in the child will affect the parent
- Treat all props as read-only — use events to communicate changes upward