Mutation and Immutability

Learn the critical difference between mutable data (like arrays) and immutable data (like strings) in JavaScript.

May 1, 20262 min read2 / 4

The Essentials

  1. Mutation Means Change: If data is mutable, it means you can alter its contents after it has been created.
  2. Arrays are Mutable: You can add, remove, or swap out elements inside an array at any time.
  3. Strings are Immutable: Primitive values like strings and numbers cannot be changed once they are created. You can only create new strings.

In JavaScript, certain values behave fundamentally differently than others. One of the biggest differences is whether a piece of data is mutable or immutable.

"Mutable" simply means "capable of being changed". Let's look at how this applies to arrays versus strings.

Arrays are Mutable

When you create an array, you are creating a collection of data that can be changed on the fly. I can access a specific index and completely reassign its value:

JavaScript
let abcArray = ["a", "b", "c"]; abcArray[1] = "d"; console.log(abcArray); // Returns ["a", "d", "c"]

The original array was successfully mutated. I swapped out "b" for "d". When I use methods like .push() or .pop(), I am also mutating the array by adding or removing items.

Strings are Immutable

Now, take a look at what happens when I try to do the exact same thing with a string:

JavaScript
let abcString = "abc"; abcString[1] = "d"; console.log(abcString); // Returns "abc"

The string did not change! But interestingly, JavaScript did not throw an error either.

Because JavaScript can be very "loosey-goosey," when you ask it to do something impossible (like mutating a string), it sometimes just ignores you and moves on without warning.

Strings, numbers, booleans, null, and undefined are all primitive types. In JavaScript, all primitive types are immutable.

Once the string "abc" is created in memory, it is locked in stone. You cannot swap out one of its characters. If you want the string "adc", you have to evaluate a completely new string and point your variable to it:

JavaScript
// This creates a brand new string and points the variable to it abcString = "a" + "d" + "c";

Understanding what data you can safely mutate (like arrays) and what data is locked in stone (like strings) will save you from spending hours tracking down bugs where your data simply refused to change.

Further Reading and Watching