Header Ads Widget

Responsive Advertisement

Const vs object.freeze

     JAVASCRIPT VARIABLES


Js const vs Object.freeze


hello guys, today's topic is What is const? and the difference between Object.freeze and const?

which one is better?

Let's understand with const. 

Const is a variable that we use to declare a variable and at the time of declaration  we have to initialize the value means we have to give some value 

What is object.freeze?

It works on value and more specifically, object values. it makes an object immutable which means we cannot change the property. 

Now here we are with today's topic const vs object.freeze 

EXAMPLE OF OBJECT.FREEZE


let obj = {
    name: "hello-world"
};
Object.freeze(obj)

here we first declare the object called obj and give a property called name and the value is " hello-world".
now in the next line, we use
Object.freeze(obj)

obj.name = "next-value "//neither we change the value nor create a new property
obj.age = 22


intentionally we want to change the value of the property called name is "next-value"
and age property value is 22

but here got an error which is, that we cannot change the value of the existing property and cannot add a new property in the obj as well.

Object.freeze method is used on an object to make its property immutable.
Once an object is frozen, its property cannot be added, deleted, or modified.

On the other side, now we understand the const workflow:

In JS, both const and Object.freeze are used to declare variables with values that cannot be changed.

Const is a keyword used to declare a variable that cannot be reassigned new value. This means that once a const variable is assigned a value that value cannot be unchanged.


for example :

// const PI = 3.14;
// PI = 3.1415; // This will throw an error

hope you understand the concept of cosnt variable and Object.freeze . if you have any doubt regarding this feel free to message us.

Post a Comment

0 Comments