HomeTutorsContact
JavaScript
How to freeze an Object in JavaScript?
Gulshan Saini
June 26, 2020
1 min

If we want an object to be immutable i.e. not change by programmer accidentally or willingly, Object.freeze is the solution. Object.freeze is a shallow freeze so the nested objects need to be frozen using recursion.

Say we have following person object that we want to freeze

Freezing Object

We can freeze the person object using Object.freeze as follows

Let’s try adding a new property on a frozen object

Now, if we try to add a new property on person object say gender it will fail silently

If we console.log the person object again we would get the original object.

Let’s try modifying existing property on a frozen object

The value of the existing properties is also frozen. Let’s try to change the age property

Again, if we log the value we still get the original object

Check if the object is frozen

We can check whether the object is frozen or not using Object.isFrozen(). It returns boolean value i.e. true or false


Tags

#javascript
Previous Article
How to convert a string to the Number type in JavaScript?

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

How to Get Current Date in Human Readable Form in JavaScript?
October 03, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media