How to Make an Object Immutable in JavaScript?

Introduced in ES5, you can use the Object.freeze() method to make an object immutable. Using Object.freeze() on an object would mean that:

  • The object can no longer be changed;
  • New properties cannot be added to the object;
  • Existing properties cannot be removed from the object;
  • Property descriptors of the object (i.e. enumerable, configurable, or writable) cannot be changed;
  • Values of existing properties cannot be changed;
  • Object prototype cannot be changed.

For example:

// ES5+
const obj = { name: 'John', age: 24 };
Object.freeze(obj);

obj.name = 'Jane';

console.log(obj.name); // 'John'

In non-strict mode, as you can see from the code above, any property changes, etc. are ignored when an object is frozen. However, in strict mode this would trigger an error:

// ES5+
use 'strict';

const obj = { name: 'John', age: 24 };
Object.freeze(obj);

// Uncaught SyntaxError: Unexpected string
obj.name = 'Jane';

You may also directly use Object.freeze() on the object at the time of assignment as the Object.freeze() method returns the same object that was passed in:

// ES5+
const obj = Object.freeze({ name: 'John', age: 24 });

console.log(obj.name); // 'John'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.