What Is Immutability?

Immutability is one of the core principles of Functional Programming.

The idea is simple:

Instead of modifying existing data, create new data with the desired changes.

This makes programs more predictable and reduces bugs caused by unexpected data modifications.

Simple Values

Suppose we have:

let age = 18;

We can change its value easily:

age = 20;

This is generally fine because numbers are simple values.

What About Objects?

Now let’s create an object:

let user = {
name: "Mohamed",
};

Unlike an Array, which stores values by index, an Object stores data as key-value pairs.

In this example:

  • name is the key.
  • "Mohamed" is the value.

Can We Replace the Object?

We could write:

let user = {
name: "Mohamed",
};
user = {
name: "John",
};

This code is valid JavaScript, but it does not follow the principle of immutability.

Why?

Because the original object has been replaced, and its previous state is lost.

In larger applications, other parts of the program may depend on the original data, so replacing it directly can introduce unexpected behavior.

The Functional Programming Approach

Instead of modifying the original object, Functional Programming creates a new object that contains the updated values.

A common JavaScript technique is the spread operator.

let user = {
name: "Mohamed",
};
const updatedUser = {
...user,
name: "John",
};

Now:

  • user still contains "Mohamed".
  • updatedUser contains "John".

The original data remains unchanged.

Note: You may also see code like this:

user.name = "John";

This is called mutation because it directly changes the existing object. It does not follow the principle of immutability.

Key Takeaways

  • Immutability means avoiding changes to existing data.
  • Functional Programming prefers creating new objects instead of modifying existing ones.
  • Changing a property like user.name = "John" is called mutation.
  • Keeping the original data unchanged makes programs safer, easier to debug, and more predictable.