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, and undefined. Reference types include objects, arrays, and functions.
Concept of Immutability
When you are developing our applications, you 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 create new objects, ensuring we’re not changing the original value.
JavaScript immutable example
A 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>
<html>
<body>
<script>
let myAge = "22";
let myNewAge = myAge;
myAge = "23";
console.log(myAge === myNewAge);
</script>
</body>
</html>
Output:
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"]
Here are some common ways to achieve immutability in JavaScript:
const Keyword: Use the const
keyword to declare variables. While const
doesn’t make objects themselves immutable, it ensures that the variable cannot be reassigned.
const myObject = { key: 'value' };
// This will throw an error:
// myObject = { newKey: 'newValue' };
Object.assign() or Spread Operator (…): Use Object.assign()
or the spread operator (...
) to create a shallow copy of an object with modifications.
const originalObject = { key: 'value' };
const modifiedObject = Object.assign({}, originalObject, { newKey: 'newValue' });
// OR
const modifiedObjectSpread = { ...originalObject, newKey: 'newValue' };
Array Methods (for Arrays): For arrays, use array methods like concat()
, slice()
, or the spread operator to create new arrays.
const originalArray = [1, 2, 3];
const modifiedArray = originalArray.concat(4);
// OR
const modifiedArraySpread = [...originalArray, 4];
Object.freeze(): Use Object.freeze()
to make an object immutable. However, this creates a shallow freeze, and nested objects may still be mutable.
const myObject = Object.freeze({ key: 'value' });
// This will throw an error:
// myObject.newKey = 'newValue';
Libraries: Consider using libraries like Immutable.js or Immer.js, which provide more advanced tools for working with immutable data structures. Immutable.js, for example, introduces persistent immutable data structures.
const { Map } = require('immutable');
const myMap = Map({ key: 'value' });
const updatedMap = myMap.set('newKey', 'newValue');
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