There are times when you don't want the data in your object to change, but unfortunately JavaScript will let you change the vaue of a key on an object at any time, even if you use the const
keyword. Luckily, there's a built in Object
class (similar to Math
like we talked about before) that provides a method called freeze
that will help make it so the object and its data is read only. But for it to work, you first need to put the file in strict mode:
'use strict';
// File contents
After that, you can call the freeze
method and pass in an object:
'use strict';
const dog = {
name: 'Max'
}
Object.freeze(dog);
Now that the object is frozen, we can't change the value of any key or add a key to the object:
dog.name = 'Duke'; // Error Cannot assign to read only property 'name' of object
dog.age = 3; // Error Cannot add property age, object is not extensible
This will work in most situations, except if you try and reassign the entire value of the variable to a new object. If your object is declared with the let
keyword, you could reassign its value to a new object, even if it's frozen. However, if you use const
, JavaScript prevents that as well. So if you use const
and Object.freeze
together, your objects should be protected pretty well.
You can read more about this in this blog post.