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)| Argument | Description |
|---|---|
obj | The 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;
configurableorwritablecannot be changed.
Checking whether an object is frozen
javascript
console.log(Object.isFrozen(user)); // trueImportant: 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
| Method | What it does | Can change values | Can add/remove properties |
|---|---|---|---|
Object.freeze() | Fully freezes | no | no |
Object.seal() | Forbids adding/removing, but allows changing values | yes | no |
Object.preventExtensions() | Forbids adding new properties | yes | yes (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 allowedSUMMARY
| Property | Behavior |
|---|---|
Object.freeze() | makes the object fully immutable |
| not allowed | adding, removing, or changing properties |
| works shallowly | nested objects remain mutable |
| check | Object.isFrozen(obj) |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.