Difference between Object.freeze and Object.seal in JavaScript
Bishnu Prasad Chowdhury
Posted on February 9, 2021
There are times when we want our objects to retain their original properties such that the property should be not changeable or editable.
We can change or add property of an object like below
var a = {
color: 'red'
};
//Object.freeze(a)
a.value = 10;
>a
[object Object] {
color: 'red',
value: 10
}
We can add Object.freeze(a); to the above code to prevent value property to be added to the a object.
Also Object.freeze(a) does not allow the property of an object to be changed.
var a = {id: 1};
a.id=5;
console.log(a);
> 5
var b = { cost: 100;};
Object.freeze(a);
b.cost= 200
console.log(a);
> 100
>delete b.cost
false
We cannot perform delete operation with an object which is freeze where on using delete it will return false.
Object.seal allows to change an existing property unlike Object.freeze
var a = { id: 6};
Object.seal(a);
a.cost=500;
a.id=10;
>a
[object Object]{
id:10
}
>delete a.id
false
So now if we want to allow delete to work on the object we can use Object.preventExtensions() instead of Object.seal()
So the below is the observation on using prevent extension
var a = {id: 6};
Object.preventExtensions(a);
a.id=9;
a.cost=100;
>a
[object Object]{
id: 9
}
> delete a.id
true
> a
[object Object] {...}
There is another way for freezing a property instead of the whole object with Object.freeze.
Suppose we want to freeze id of an object a only rather than the whole object, we can use it like below
var a = { id : 5, cost : 100, quantity: 50};
Object.defineProperty( a, 'id', { writable: false, value:5});
a.id = 10;
a.quantity=10
a.cost= 60
>a
[object Object]{
id:5,
cost:60,
quantity: 10
}
Posted on February 9, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024