How Does Understanding Immutability in JavaScript Work?

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!

Take the quiz →

Examples

  1. A variable like let name = 'Alice'; can change, but if you use const, it stays the same.
  2. When you copy an object in JavaScript, changes to the original don't affect the copy.
  3. If you have a list of names and add one more, the old list doesn’t change.

Ask a question

See also

Discussion

Recent activity