JavaScript Object freeze() Method
Last Updated :
26 May, 2023
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.
Examples of the above function are provided below.
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”.
Javascript
const obj1 = { property1: 'initial_data' };
const obj2 = Object.freeze(obj1);
obj2.property1 = 'new_data' ;
console.log(obj2.property1);
|
Output :
"initial_data"
Example 2: In this example, the object “obj” has been assigned “prop: function” which has been later deleted since the object “obj wasn’t frozen. After that, a new object “o” has been assigned the frozen values of “obj” which prevented it from further updations.
Javascript
let obj = { prop: function () { }, name: 'adam' };
console.log(obj);
obj.name = 'billy' ;
delete obj.prop;
console.log(obj);
let o = Object.freeze(obj);
obj.name = 'chris' ;
console.log(obj);
|
Output :
Object { prop: function () {}, name: "adam" }
Object { name: "billy" }
Object { name: "billy" }
Applications:
- Object.freeze() is used for freezing objects and arrays, o make an object immutable.
We have a complete list of Javascript Object methods, to check those please go through this JavaScript Object Complete Reference article.
Supported Browsers:
- Google Chrome 6.0 and above
- Internet Explorer 9.0 and above
- Mozilla 4.0 and above
- Opera 11.1 and above
- Safari 5.0 and above
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...