
Immutability in JavaScript
It’s a mutation. It’s a very groovy mutation. I’ve got news for you, Amy. You are a mutant. — Professor X
Before I address the topic of immutability, let’s first understand what mutation means.
Mutation
Anything that changes or transforms the behavior or structure of an object is called a mutation — like the force mutating Goku in the above picture.
Mutation in JavaScript
This concept in JavaScript refers to changing the contents of a variable, particularly objects or arrays.
Why is mutation a problem in JavaScript?
To answer this, we need to understand:
Pass by Value
let a = 5;
let b = a;
a = 15;
b
remains 5 even after a
changes — because primitive types (like numbers) are passed by value.
Pass by Reference
let object1 = { name: "goku" };
let object2 = object1;
object1.name = "charan";
object2.name
will also be "charan"
because objects are passed by reference — both variables point to the same memory.
Both object1
and object2
point to the same memory location.
Arrays behave the same way:
Why is this bad?
If you pass an object or array into multiple functions and one of them mutates it, you may get unexpected side effects, leading to bugs.
Solution: Going Immutable!
Using Object.assign()
const object2 = Object.assign({}, object1, { name: "charan" });
This creates a new object, ensuring object1
and object2
are independent.
Using the spread operator
const object2 = { ...object1, name: "charan" };
Cleaner syntax, same result — a new object without mutating the original.
For arrays:
const newArr = [...arr, 6];
This appends to the array immutably.
Also useful:
These all return new arrays and don’t mutate the original.
Final Thoughts
Writing immutable JavaScript code helps avoid bugs, makes your functions pure, and improves maintainability.
I hope this article gives you a basic understanding of:
- How variables behave in memory
- Why immutability matters
- How to write cleaner, safer code in JavaScript
Feedback and suggestions are welcome. 🙂