The Object.freeze() method is used to freeze an object. Freezing an object does not allow new properties to be added to the object and prevents removing or altering the existing properties. Object.freeze() preserves the enumerability, configurability, writability, and prototype of the object. It returns the passed object and does not create a frozen copy.
Syntax:
Object.freeze(obj)
Parameters:
- obj: It is the object which has to be frozen.
Return Value: Object.freeze() returns the object that was passed to the function.
Example 1: In this example, the object “obj2” has been assigned property from object “obj1”, and the properties of “obj1” are frozen therefore new properties and values are prevented from being added to “obj2”.
// creating an object constructor and assigning values to it
let obj = { prop: function () { }, name: ‘adam’ };
// Displaying the properties of the object created
console.log(obj);
// Updating the properties of the object
obj.name = ‘billy’;
delete obj.prop;
// Displaying the updated properties of the object
console.log(obj);
// Freezing the object using object.freeze() method
let o = Object.freeze(obj);
// Updating the properties of the frozen object
obj.name = ‘chris’;
// Displaying the properties of the frozen object –>
console.log(obj);
Output :
Object { prop: function () {}, name: "adam" }
Object { name: "billy" }
Object { name: "billy" }