JavaScript .freeze()
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. It 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)
obj: It is the object which has to be frozen.
Examples
The following codes demonstrate a basic implementation of the Object.freeze() method:
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 itconst obj1 = { property1: 'initial_data' };// creating a second object that will freeze the properties of the first objectconst obj2 = Object.freeze(obj1);// Updating the properties of the frozen objectobj2.property1 = 'new_data';console.log(obj2.property1);
The above code snippet will return the following 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:
// creating an object constructor and assigning values to itlet obj = { prop: function () {}, name: 'adam' };console.log(obj);// Updating the properties of the objectobj.name = 'billy';delete obj.prop;console.log(obj);// Freezing the object using object.freeze() methodlet o = Object.freeze(obj);// Updating the properties of the frozen objectobj.name = 'chris';console.log(obj);
The above code snippet will return the following output:
{ prop: [Function: prop], name: 'adam' }{ name: 'billy' }{ name: 'billy' }
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Learn how to build back-end web APIs using Express.js, Node.js, SQL, and a Node.js-SQLite database library.
- Includes 8 Courses
- With Certificate
- Beginner Friendly.30 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours