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() −


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

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

node fileName.js.


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


Kickstart Your Career

Get certified by completing the course

Get Started