🍈Immutability

Immutability refers to the concept of not being able to change the value of an object or variable once it has been created. This means that, once you have created an object or variable, you cannot modify its value directly. Instead, you must create a new object or variable with the modified value.

There are a few ways you can achieve immutability in JavaScript:

  • Using the Object.freeze() method: This method freezes an object, which means that you cannot add, delete, or modify any of its properties. However, you can still access the properties of a frozen object.

const obj = {
  name: 'John',
  age: 30
};

Object.freeze(obj);

obj.name = 'Sara'; // This will have no effect, because the object is frozen
console.log(obj.name); // 'John'

Using the Object.assign() method: This method creates a new object and copies the properties of an existing object into it. You can use it to create a modified version of an object without changing the original object.

const obj = {
  name: 'John',
  age: 30
};

const updatedObj = Object.assign({}, obj, { age: 31 });

console.log(obj.age); // 30
console.log(updatedObj.age); // 31

Using the spread operator (...): This operator allows you to create a new array or object that includes the values of an existing array or object. You can use it to create a modified version of an array or object without changing the original.

const arr = [1, 2, 3];

const updatedArr = [...arr, 4];

console.log(arr); // [1, 2, 3]
console.log(updatedArr); // [1, 2, 3, 4]

Using immutability in your code has several benefits, including:

  • Simplifying debugging: If you are not able to change the value of an object or variable, you can be sure that its value has not been modified unexpectedly. This can make it easier to identify the cause of an error or bug.

  • Improving performance: If you create a new object or array each time you need to modify an existing one, you may see a performance boost because JavaScript's garbage collection process will be able to clean up the old objects and arrays more efficiently.

  • Enabling functional programming: By not modifying the value of an object or variable, you can avoid side effects and create pure functions that are easier to test and reason about.

Last updated