How to Make an Object Immutable in JavaScript?

Find out how you can prevent a JavaScript object from being mutated

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'

Hope you found this post useful. It was published . Please show your love and support by sharing this post.