Saturday, 15 February 2020

How to prevent modifying an Object – JavaScript

JavaScriptObjectFreezeSeal

In this article we are going to discuss about some JavaScript cool features which can prevent Object from modifying, adding a new property etc.

1. Freeze JavaScript Object
2. Seal JavaScript Object

Sample Object


const myObject = {
      name: 'Prashobh',
      status: 'JavaScript Developer'
    }

1. Freeze JavaScript Object

Here we are freezing the object that means you wont be able to modify or add a new property.


const myObject = {
      name: 'Prashobh',
      status: 'JavaScript Developer'
    }

Object.freeze(myObject);

Now try to modify the value.


myObject.name = 'another name';

You will be getting below console error.


Cannot assign to read only property 'name' of object '[object Object]'

Now try to add new property.


myObject['country'] = 'USA';


Cannot add property country, object is not extensible

Important note: You should run this in strict mode, use: 'strict'

2. Seal JavaScript Object

In this scenario you can modify the values but wont be able to add new properties. For example,


const myObject = {
      name: 'Prashobh',
      status: 'JavaScript Developer'
    }

Object.seal(myObject);

This way you will be able to update the values. For example you can do myObject.name = 'another name';. Now try to add new property.


myObject['country'] = 'USA';


Cannot add property country, object is not extensible

You cannot delete the property as well.

You can use below method to identify whether the Object is freezed or sealed. It will return true or false


Object.isFrozen(myObject).

Object.isSealed(myObject).

Object.isExtensible(myObject).

In this article we have discussed about Freezing and sealing a JavaScript Objects.

Related Info

1. How to solve JavaScript heap out of memory issue in Angular project.

2. How to rename key of an Object.

3. Remove duplicate by using one line of code – JavaScript

No comments :

Post a comment