Sitemap
Muhammad Faraz Ali

Muhammad Faraz Ali

Strong believer, Highly motivated and a self learner Software Engineer. Tech stack: JavaScript, React, Next and React Native.

Object.seal() vs Object.freeze() in JavaScript

1 min readMar 26, 2023

Both methods allow you to control the mutability of objects, but they have different behaviors.

1-Object.seal(obj):

This method seals an object, which means that you can’t add or delete properties, but you can still modify the values of existing properties.

let obj = {
a: "a",
b: "b",
};
Object.seal(obj);
obj.a = 2; //allowed
delete obj.b; //Not allowed
obj.c = "c"; //Not allowed
console.log(obj); // {a: 2, b: "b"};

2-Object.freeze(obj):

Get Muhammad Faraz Ali’s stories in your inbox

Join Medium for free to get updates from this writer.

This method freezes an object, which means that you can’t add, delete or modify the values of existing properties. This method makes completely read-only objects.

let obj2 = {
a: "a",
b: "b",
};
Object.freeze(obj2);
obj2.a = 2; //Not Allowed
delete obj2.b; //Not Allowed
obj2.c = "c"; //Not Allowed
console.log(obj2); // {a: "a", b: "b"}; //remains same

3-Object.preventExtensions(obj):

This method prevents objects from extensions, which means you can’t add properties to the object, but you can add and delete the object's existing properties.

let obj3 = {
a: "a",
b: "b",
};
Object.preventExtensions(obj3);
obj3.a = 2; //Allowed
delete obj3.b; //Allowed
obj3.c = "c"; //Not Allowed
console.log(obj3); // { a: 2 }//modified object

Summary:

Press enter or click to view image in full size

--

--

Muhammad Faraz Ali
Muhammad Faraz Ali

Written by Muhammad Faraz Ali

Strong believer, Highly motivated and a self learner Software Engineer. Tech stack: JavaScript, React, Next and React Native.