How to disallow altering of object variables in JavaScript?


Use the concept of freeze() from JavaScript to disallow adding new properties to an object, altering of object properties, etc.

Following is the code wherein we are changing the value but the previous value still remains since we cannot alter properties using freeze() −

Example

const canNotChangeTheFieldValueAfterFreeze = {value1 : 10,value2: 20 };
Object.freeze(canNotChangeTheFieldValueAfterFreeze);
canNotChangeTheFieldValueAfterFreeze.value = 100;
console.log("After changing the field value1 from 10 to 100
="+canNotChangeTheFieldValueAfterFreeze.value1);

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo97.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo97.js
After changing the field value1 from 10 to 100 =10

Updated on: 07-Sep-2020

51 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements