JavaScript – how to prevent changes to an object attributes

Whenever you want to make a variable constant, in order to not be able to change(mutate) it through the program, then you gonna need to define the variable to const like this:

The thrown message on the console is :

(index):49 Uncaught TypeError: Assignment to constant variable.
at window.onload ((index):49)

And that is the purpose of the const declaration.

What happen’s if we do the same for an object variable ?
Let’s figure out on the next snippet code :

So after trying to do the assignment object to the userObject, we get an error as we expected:

Uncaught TypeError: Assignment to a constant variable.
at window.onload ((index):56)

Now we are going to change the attributes of the object, so in this case, let’s change the family attribute value on the next line of code:

As you see above console.log( printed the correct new update without any error.

So to prevent this you need to use a function called freeze:

As you see above after we changed the family value, even though we didn’t get any error, we still successfully didn’t make any change to the userObject’s family attribute.

To check if an object is frozen, use the next method:

To get additional deep knowledge on the freeze method, here is the link

I hope you enjoyed, thanks for reading this tiny post.


Hello, I'm Mohammad Daka, software engineer who love coding. In my spare time I blogs about JavaScript,PHP, Chrome Extensions, helpful resources and tools, I'm also working on my own projects. Don't hesitate to contact me at my twitter account: @mohammad_daka :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *