Object.freeze() vs const

Object.freeze() vs const

In this post, we’re going to explore the difference between const keyword and the Object.freeze method and understand how we could utilize these features to gain better control over our object properties.

const

The const keyword was introduced with ES6 as a way to create constant variables in JavaScript. It is used to create an immutable binding i.e. you cannot re-assign a new value to a variable created using const keyword.

const person = { name: 'Harshal' }
person = { name: 'John' } // Uncaught TypeError: Assignment to constant variable.

The above code will trigger error as we’re trying to assign a new value to person variable.

However, one point we need to understand is const keyword makes the binding of the variable immutable, not the value itself. Let’s understand this using an example.

const person = { name: 'Harshal' }
person.name = 'John';
console.log(person.name); // John

As you can see in the above example, we can change the value of the property name on the object person even after being assigned.

Object.freeze

Object.freeze is used to freeze an object. Once an object is frozen no value modifications are allowed on that object. Let’s understand this in detail using a code sample.

let person = Object.freeze({ name: 'Harshal' });
person.name = 'John';
console.log(person.name) // Harshal

As you can see in the above code, although we’re modifying the value of name property it is simply ignoring all the modifications and simply holding on to the value used while freezing the object.

One important thing to note is the Object.freeze method makes the object immutable not the binding i.e it is possible to re-assign a new value to a frozen variable.

let person = Object.freeze({ name: 'Harshal' });
person.name = 'John';
console.log(person.name); // Harshal

person = Object.freeze({ name: 'John' });
console.log(person.name); // John

As you can see in the above code, we’re not able to modify the value the person but we can assign a new value to the object.

Must Read: Angular Meta Service for Meta Tags

Conclusion

The const keyword creates immutable bindings i.e you cannot assign a new value to a variable once it is created however you can modify the existing values of the constant.

The Object.freeze method creates immutable object i.e. it’ll not allow you to modify, create or delete properties of a frozen object but it doesn’t prevent you from assigning a new value to the object.

Leave a Reply

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