JavaScript Object.freeze()

The Object.freeze() method freezes an object i.e. it prevents the object from being modified.

Example

let obj = {
  prop: function () {},
  foo: "bar",
};

// freeze the object Object.freeze(obj)
// changes will not occur obj.foo = "bar1"; console.log(obj.foo); // Output: bar

freeze() Syntax

The syntax of the freeze() method is:

Object.freeze(obj)

Here, freeze() is a static method. Hence, we need to access the method using the class name, Object.

Notes: A frozen object can no longer be changed. Freezing an object prevents:

  • New properties from being added to the object.
  • Existing properties to be removed from the object.
  • Changing the enumerability, configurability, or writability of existing properties.
  • Changing the values of existing object properties and prototypes.

freeze() Parameters

The freeze() method takes in:

  • obj - the object to freeze.

freeze() Return Value

The freeze() method returns:

  • The object that was passed to the function.

Notes:

  • Any attempt to add or remove from the property set of frozen objects will either fail silently or the program will throw TypeError (mostly when in strict mode).
  • Objects sealed with Object.seal() can have their existing properties changed while Object.freeze() makes the existing properties immutable.

Example: JavaScript Object.freeze()

let obj = {
  prop: function () {},
  foo: "bar",
};

// freeze the obj object let o = Object.freeze(obj);
// changes will fail silently obj.foo = "bar1"; console.log(obj.foo);
// cannot add a new property obj.new_foo = "bar"; console.log(obj.new_foo);

Output

bar
undefined

In the above example, we have created an object obj with two properties: prop and foo.

We then used the Object.freeze() method to freeze obj, which makes it immutable. Once an object is frozen, its properties cannot be modified or deleted.

The output indicates that any attempt to modify a property or add a new property on a frozen object will fail silently without throwing an error.

Note: Object.freeze(obj) only applies to the immediate properties of obj. If the values of those properties are objects themselves, those objects are not frozen and may be the target of property addition, removal, or value reassignment operations.


Also Read:

Did you find this article helpful?