Object.freeze() in Javascript🎈

olawanle_joel

Joel Olawanle

Posted on May 14, 2020

Object.freeze() in Javascript🎈

I was reading a post here on dev.to 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,

Example:

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.

GREETING.name = "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); 

GREETING.name = "Elijah"; // This will now be ignored due to mutation
Enter fullscreen mode Exit fullscreen mode

For more clarification check:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/prevent-object-mutation

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

💖 💪 🙅 🚩
olawanle_joel
Joel Olawanle

Posted on May 14, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related