Skip to main content

What does Object.freeze() do?

Object.freeze() is a built-in JavaScript method that "freezes" an object, making it fully immutable: properties cannot be changed, removed, or added.


In short

Syntax:

javascript
Object.freeze(obj)
ArgumentDescription
objThe object to "freeze"

Returns the same object, but with frozen properties.


Example - freezing an object

javascript
const user = { name: 'Bohdan', age: 25 }; Object.freeze(user); user.name = 'Oleh'; // will not change user.city = 'Kyiv'; // cannot add a new one delete user.age; // cannot delete console.log(user); // { name: 'Bohdan', age: 25 }

After Object.freeze() the object becomes immutable:

  • properties cannot be overwritten;
  • new ones cannot be deleted or added;
  • configurable or writable cannot be changed.

Checking whether an object is frozen

javascript
console.log(Object.isFrozen(user)); // true

Important: the freeze is shallow

If there are nested objects inside, they remain mutable:

javascript
const user = { name: 'Bohdan', address: { city: 'Kyiv' } }; Object.freeze(user); user.address.city = 'Lviv'; // works! console.log(user.address.city); // "Lviv"

So Object.freeze() protects only the top level. For a "deep" freeze you need to freeze recursively.


Example of a deep freeze

javascript
function deepFreeze(obj) { Object.freeze(obj); for (const key in obj) { if (typeof obj[key] === 'object' && obj[key] !== null && !Object.isFrozen(obj[key])) { deepFreeze(obj[key]); } } return obj; } const user = { name: 'Bohdan', address: { city: 'Kyiv' } }; deepFreeze(user); user.address.city = 'Lviv'; // will not change console.log(user.address.city); // "Kyiv"

Now the object and all its content are fully "frozen".


Difference from other methods

MethodWhat it doesCan change valuesCan add/remove properties
Object.freeze()Fully freezesnono
Object.seal()Forbids adding/removing, but allows changing valuesyesno
Object.preventExtensions()Forbids adding new propertiesyesyes (existing ones can be removed)

Example: freeze vs seal

javascript
const user = { name: 'Bohdan' }; Object.seal(user); user.name = 'Oleh'; // allowed delete user.name; // not allowed Object.freeze(user); user.name = 'Max'; // not allowed

SUMMARY

PropertyBehavior
Object.freeze()makes the object fully immutable
not allowedadding, removing, or changing properties
works shallowlynested objects remain mutable
checkObject.isFrozen(obj)

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.