Skip to content

Instantly share code, notes, and snippets.

@SantoshCode
Created April 17, 2021 00:19
Show Gist options
  • Save SantoshCode/886d5c612986620aa8689dd82ca71a75 to your computer and use it in GitHub Desktop.
Save SantoshCode/886d5c612986620aa8689dd82ca71a75 to your computer and use it in GitHub Desktop.
Immutability in JavaScript

Mutable and Immutable Data Types

Textbook Definition

A mutable object is an object whose state can be changed or modified over time. A immutable object is an object whose state cannot be modified after it is created.

In Javascript String and Numbers are immutable and Objects and arrays ars mutable.

let a = 7
a += 1

because you can’t change its value. For example, you can’t literarily change the value of 7 to 8. That doesn’t make sense. Instead, you can change the value stored in the variable x from 7 to 8.

Strings are also immutable too, and this is obvious when you try to change a particular character in a string.

let str = "I am immutable"
str[2] = 'c'
console.log(str) // I am immutable

Mutability doesn't make much sense for "single value" values, because mutating such a value basically means replacing it with a different value "in place".

What we see is that for mutable values, updating state applies across all references to that variable. So changing a value in one place, changes it for all references to that object. For the immutable data types, we have no way of changing the internal state of the data, so the reference always gets reassigned to a new object. The biggest implication of this is that for immutable data, equality is more reliable since we know that a value’s state won’t be changed out from under us.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment