Understand the difference between how data is stored and manipulated in JavaScript with real-world examples.
🔹 What is Mutability?
In programming, mutability refers to whether or not a value can be changed after it's created.
- Mutable: You can change it.
- Immutable: You can't change it, you can only create a new copy.
JavaScript handles primitive and reference data types differently in terms of mutability. Let’s explore that.
🧾 Primitive Data Types (Immutable)
Primitive values in JavaScript include:
String
Number
Boolean
undefined
null
Symbol
BigInt
These are immutable – meaning, once a primitive value is created, it cannot be changed. Any operation that looks like it's changing a value actually creates a new value.
✅ Example:
let name = "John";
let newName = name; // Copy by value
newName = "Doe";
console.log(name); // John
console.log(newName); // Doe
Here, changing newName
doesn't affect name
because strings are primitives and copied by value, not by reference.
📦 Reference Data Types (Mutable)
Reference types include:
Object
Array
Function
These are mutable, and when you assign them to a variable, you're assigning a reference to the object in memory, not the actual value.
✅ Example of Mutability:
let user = { name: "Alice" };
let newUser = user; // Copy by reference
newUser.name = "Bob";
console.log(user.name); // Bob
console.log(newUser.name); // Bob
Even though we updated newUser
, it also affected user
because both point to the same object in memory.
✅ Making Reference Types Immutable (Using Spread Operator or Object.assign
)
If you want to keep your reference data immutable (best for state management, especially in React), you need to create copies.
Example using Spread Operator:
let original = { city: "Paris" };
let copied = { ...original };
copied.city = "London";
console.log(original.city); // Paris
console.log(copied.city); // London
Here, changing copied
does not affect original
.
🧠 Why Immutability Matters?
- Predictability: Code is easier to debug and reason about.
- State Management: Essential in frameworks like React.
- Avoid Side Effects: Prevent accidental changes in data.
⚡ Quick Summary
Type | Mutable? | Copied By | Example |
---|---|---|---|
String , Number
|
❌ No | Value | let a = b |
Object , Array
|
✅ Yes | Reference | let a = b |
💡 Final Thoughts
Understanding the difference between immutable and mutable values is a must-have skill for writing clean, bug-free JavaScript code. Stick to immutability where possible—it’ll save you a lot of headaches down the road.
Top comments (0)