JS Coding Questions Logo
JS Coding Questions
#179💼 Interview💻 Code

What is the freeze method

Advertisement

728x90

The freeze() method is used to freeze an object. Freezing an object does not allow adding new properties to an object, prevents removing, and prevents changing the enumerability, configurability, or writability of existing properties. i.e. It returns the passed object and does not create a frozen copy.

javascript
1const obj = {
2  prop: 100,
3  };
4
5Object.freeze(obj);
6
7obj.prop = 200; // Throws an error in strict mode
8
9console.log(obj.prop); //100

Remember freezing is only applied to the top-level properties in objects but not for nested objects.

For example, let's try to freeze user object which has employment details as nested object and observe that details have been changed.

javascript
1const user = {
2  name: "John",
3  employment: {
4  department: "IT",
5  },
6  };
7
8Object.freeze(user);
9
10user.employment.department = "HR";

Note: It causes a TypeError if the argument passed is not an object.

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 8

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
179of476