Creating Immutable Objects in JavaScript

September, 23rd 2024 1 min read

Mutable vs Immutable in JavaScript

In JavaScript, the terms mutable and immutable refer to whether a value or object can be changed after it is created. Understanding this distinction is important for writing predictable and bug-free code.

Mutable

Mutable objects can be changed or modified after they are created.

js
let person = { name: 'John', age: 30 };
person.age = 35;

Immutable

Immutable values cannot be altered once created.

js
let name = 'John';
let newName = name.toUpperCase();

Why Immutability Matters

  • Predictability
  • No side effects
  • Better functional programming

1. Using Object.freeze()

js
const person = { name: 'John', age: 30 };
Object.freeze(person);
person.age = 35; // ignored

2. Deep Freeze

js
function deepFreeze(obj) {
  Object.keys(obj).forEach(prop => {
    if (typeof obj[prop] === 'object' && obj[prop] !== null) {
      deepFreeze(obj[prop]);
    }
  });
  return Object.freeze(obj);
}

3. Using const for Primitive Values

js
const name = 'John';

4. Using Immutable.js

js
const { Map } = require('immutable');
const person = Map({ name: 'John', age: 30 });

5. Using Object.defineProperty()

js
const person = {};
Object.defineProperty(person, 'name', { value: 'John', writable: false });

6. Using Spread Operator

js
const updated = { ...person, age: 35 };

Conclusion

Immutability helps avoid bugs and keeps your data consistent.