Understanding immutability in JavaScript is like having a toy box that you can’t change once it's set up, only make new ones.
Imagine you have a red ball in your toy box. That’s your variable. Now, if you want to add a blue block, instead of changing the red ball, you just make a brand-new toy box with both the red ball and the blue block inside. That’s what immutability does, it keeps the old one as is and makes a new copy with the changes.
Like Making a New Sandwich
Think about making a sandwich. If you want to add cheese to your plain peanut butter sandwich, you don’t rewrite the whole sandwich, you just make a new one with cheese added. The original peanut butter sandwich stays exactly how it was.
In JavaScript, when something is immutable, like a number or a string, you can't change it directly. Instead, you create a new version with the changes, and the old one stays untouched.
So, immutability helps keep things simple and predictable, no surprises when your toy box (or your code) changes!
Examples
- When you copy an object in JavaScript, changes to the original don't affect the copy.
Ask a question
See also
- How Does Immutability - Computerphile Work?
- What is immutability?
- How Does Every React Concept Explained in 12 Minutes Work?
- How Does Functional programming - A general introduction Work?
- How Does C++ while loops explained 🔃 Work?