Skip to content

JavaScript immutable | Basics

JavaScript Immutable is a type of variable that can’t be changed. In JavaScript primitive types are immutable (or unchangeable), and the reference types are mutable (changeable).

Primitive types include numbers, strings, boolean, null, undefined. And reference types include objects, arrays and functions.

Concept of Immutability

When you are developing our applications, might end up in some situations where you want to create a new object in our code, containing a new property or value while also maintaining the original value. The concept of immutability can help us to create new objects, making sure that we’re not changing the original value.

JavaScript immutable example

Simple example code created two variables and assigned the myAge to the myNewAge variable. But after we changed the value of myAge, we will see that they’re not the same.

<!DOCTYPE html>
    let myAge = "22";

    let myNewAge = myAge;

    myAge = "23";

    console.log(myAge === myNewAge); 



JavaScript immutable

Primitive values cannot be changed by reassignment.

var str = "testing";
var str = "testing,testing";
console.log(str); // testing, testing

But object can

var fruits = ["apple", "banana", "orange"];

fruits[0] = "mango";

console.log(fruits); //["mango", "banana", "orange"]

Do comment if you have any doubts or suggestions on this JS immutable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *