Question

10.

What is Immutability or Immutable Declarations in JavaScript

Answer

In JavaScript, immutable declarations refer to variables that cannot be reassigned after their initial assignment. This immutability is achieved using the const keyword, which stands for "constant". When you declare a variable with const, its value cannot be changed through reassignment. However, it's important to note that const only prevents reassignment of the variable itself, not the modification of the object it might reference.

Basic Usage of const

const PI = 3.14159;
PI = 3.14; // TypeError: Assignment to constant variable.

In this example, attempting to reassign a value to PI will result in a TypeError because PI was declared with const.

Immutability and Objects

While const prevents variable reassignment, it does not make the value itself immutable. This means that if the value is an object (including arrays and functions), the properties or elements of that object can still be altered.

const myObject = { key: 'value' };
myObject.key = 'newValue'; // This is allowed
myObject = {}; // TypeError: Assignment to constant variable.

const myArray = [1, 2, 3];
myArray.push(4); // This is allowed
myArray = []; // TypeError: Assignment to constant variable.

In these examples, modifying the contents of myObject and myArray is allowed, but attempting to reassign a new object or array to myObject or myArray results in a TypeError.

Ensuring True Immutability

To ensure true immutability of an object in JavaScript (where neither the object itself nor its properties can be changed), you would need to use Object.freeze() in conjunction with const. However, Object.freeze() is shallow, meaning it only applies to the immediate properties of the object. Nested objects would need to be individually frozen to achieve deep immutability.

const myObject = Object.freeze({ key: 'value' });
myObject.key = 'newValue'; // Fails silently in non-strict mode, TypeError in strict mode

For deeper levels of immutability, you would have to recursively apply Object.freeze() to objects within objects. There are libraries available, such as Immutable.js, that can help manage and enforce immutability more comprehensively in complex applications.

Support us ❤️

Buy Us A Coffee