loading...

Object.freeze() in JavascriptšŸŽˆ

olawanle_joel profile image Joel Olawanle 惻1 min read

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

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!"
 }

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";

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

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.

Posted on May 14 by:

Discussion

markdown guide