DEV Community

Joel Olawanle
Joel Olawanle

Posted on

Object.freeze() in Javascript🎈

I was reading a post here on which explained the difference between var, let and const by Sarah Chima.

The article was well explained but what I would love to explain in this article is the const variable declaration.

The const variable declaration cannot be reassigned and updated, that's very true but in the case of arrays, objects we could still update their values. So the Object. freeze method helps us freeze our data or variable to protect our data from mutation.

const name = "Joel"
name = "John" //this will throw an error
Enter fullscreen mode Exit fullscreen mode

const alone does not guarantee protection for your data or let me say it does not protect your data from mutation,


const GREETING = {
    name : "Joel",
    info : "Goodday!"
Enter fullscreen mode Exit fullscreen mode

Though the above code makes use of const I can still update the values via the code below since it's an object or an array. = "Elijah";
Enter fullscreen mode Exit fullscreen mode

But this could easily be avoided by making use of Object.freeze() to freeze our const variables.
Just add this line of code and you will discover that the values cannot be updated.

Object.freeze(GREETING); = "Elijah"; // This will now be ignored due to mutation
Enter fullscreen mode Exit fullscreen mode

For more clarification check:

p.s: I'm looking forward to being your friend🚀 let's connect on twitter.

Top comments (0)