Back to Home
Objects

How to Make Objects Immutable

Use Object.freeze() to make objects immutable

Quick Answer (2024 ES6+ Way)

javascript
const config = Object.freeze({
  apiUrl: 'https://api.example.com',
  timeout: 5000
});
config.timeout = 3000; // Fails silently (or throws in strict mode)
console.log(config.timeout); // 5000

Live Example

javascript
const constants = Object.freeze({
  PI: 3.14159,
  MAX_SIZE: 100,
  STATUS: Object.freeze({
    PENDING: 'pending',
    COMPLETE: 'complete'
  })
});

// Attempts to modify will fail
constants.PI = 3.14; // No effect
constants.NEW_PROP = 'value'; // No effect

console.log(constants.PI); // 3.14159

// Deep freeze function
function deepFreeze(obj) {
  Object.freeze(obj);
  Object.values(obj).forEach(value => {
    if (typeof value === 'object' && value !== null) {
      deepFreeze(value);
    }
  });
  return obj;
}

Common Variations

Object.seal()
javascript
const sealed = Object.seal(obj);
// Can modify existing props, can't add/delete
Check if Frozen
javascript
const isFrozen = Object.isFrozen(obj);
const isSealed = Object.isSealed(obj);

❌ Don't Do This (Outdated Way)

Avoid thinking freeze is deep by default

javascript
// DON'T DO THIS
const obj = Object.freeze({ nested: { val: 1 } });
obj.nested.val = 2; // This WILL work - freeze is shallow

Browser Support

Works in all modern browsers (ES5+)

#objects#immutable#freeze