How to prevent JavaScript object from mutating?

 In this post we will look in to a way to prevent object from mutating. Using only const will not effectively prevent an obj form mutating.

So what we need to use is a method called Object.freeze().

 This method will prevent any attempt at changing the object and will throw an error if the code is running in strict mode. 

let obj = {
  1: "apple",
  2: "banana",
  3: "chocolate",
};
Object.freeze(obj);
try {
  obj[10] = "vanilla";
  console.log(obj);
  // { '1': 'apple', '2': 'banana', '3': 'chocolate' } vanilla was not added
// to the object.
 
} catch (error) {
  console.log(error); // this will be fired when running in strict mode
}

When we use the freeze method on the obj and try to add vanilla, It was not added.




Comments