What is the main difference between Object.freeze() and const in JavaScript?

JavascriptFront End TechnologyObject Oriented Programming

The difference between Object.freeze() and const is that the former prevents mutability whereas the latter doesn't prevent mutability. For better understanding lets' discuss them individually.

Const

Const behavior is same as that of let. Once any variable is defined using const it cannot be reassigned. Variables declared by Const are block scoped and not function scoped as defined by var.

The main drawback with const key word is that it doesn't prevent object from mutability. The properties of the object can be changed even though that object is defined using const. This is called mutability. There is a generalization that any variable that is assigned using const cannot be reassigned again. But when an object is defined using const, its properties can be changed. In that scenario it is better to avoid const to prevent mutability.

Example

In the following example initially the value of property 'country' is "India". But later on the value is changed to England even though the variable is assigned using const.

Live Demo

<html>
<body>
<script>
   const person = {
      "name" : "Suresh",
      "Country" : "India",
      "Designation" : "Mayor"
   }
   person.Country = "England"
   document.write(person.Country);
</script>
</body>
</html>

Output

England

Object.freeze()

This method provides immutability. Once any object is frozen, its properties cant be changed. 

In the following even though the value of property "country" is changed from"India" to "England", because of immutability the value "India" retains its place.

Example

Live Demo

<html>
<body>
<script>
   const person = {
      "name" : "Suresh",
      "Country" : "India",
      "Designation" : "Mayor"
   }
   Object.freeze(person);
   person.Country = "England"
   document.write(person.Country);
</script>
</body>
</html>

Output

India

raja
Published on 28-Jun-2019 12:41:31
Advertisements