Sales1 min read137 words

How to use Object.freeze() in JavaScript?

Erkan Sivas

PlusClouds Author

Cloud & SaaS

How to use Object.freeze() in JavaScript?

Objects and arrays in JavaScript are mutable. This means that we can change an object (or an array) whenever we want. But if we don't want that to happen for any reason and want to make the object immutable.


We can do this using the freeze() method.


An object that you freeze with the freeze() method can no longer be changed; freezing an object with freeze prevents adding new properties, removing existing properties, changing the enumerability, configurability, or writability of existing properties, and changing the values of existing properties. Additionally, freezing an object also prevents the prototype from being modified.


I can add an example code regarding the usage of this method;
const obj = {
    name: "Jack"
};

Object.freeze(obj);

obj.name = "Kelly";
// Throws an error in strict mode

console.log(obj.name);
// expected output: "Jack"



#There is no text provided for translation. Please provide the text you would like to be translated into English.

Veelgestelde Vragen

What does Object.freeze do in JavaScript and what parts of an object does it affect?

Object.freeze makes an object immutable by preventing adding new properties, removing existing properties, or changing the enumerability, configurability, or writability of existing properties, and by preventing changes to their values. It also prevents the object's prototype from being modified.

Can I still read property values from a frozen object?

Yes. After freezing, you can still read property values; for example, obj.name would print 'Jack'.

What happens if I try to change a property on a frozen object?

You cannot change a frozen object's properties; attempting to assign a new value will throw an error in strict mode.

Does freezing an object also prevent modifying its prototype?

Yes. Freezing an object also prevents the prototype from being modified.

How do I freeze an object in code?

Use Object.freeze on the object, for example: const obj = { name: 'Jack' }; Object.freeze(obj); After freezing, attempts to change properties will throw an error in strict mode.

What happens to existing properties after freezing?

Freezing prevents changing the values of existing properties. It also prevents changing the enumerability, configurability, or writability of those properties.