DEV Community

Alish Giri
Alish Giri

Posted on

Declaration using const vs freeze in Javascript

Javascript const

Using const we can still modify the contents of a Javascript objects but the reference to this object will be immutable.

const product = {name: "Sugar", weight: "1 kg"}; product.name = "Some New Name"; console.log(product); 
Enter fullscreen mode Exit fullscreen mode
{ name: "Some New Name", weight: "1 kg" } 
Enter fullscreen mode Exit fullscreen mode

Javascript freeze

Using freeze is preferred in cases where we do not want to modify the contents of an object.

const product = {name: "Sugar", weight: "1 kg"}; Object.freeze(product); product.name = "Some New Name"; console.log(product); 
Enter fullscreen mode Exit fullscreen mode
{ name: "Sugar", weight: "1 kg" } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)