What are the differences between freeze, seal and preventExtensions?

Object.freeze, Object.seal, and Object.preventExtensions all three methods are from Object in JavaScript. These methods are used to control the access level of an object. They have a few differences. We are going to discuss those in the following section:

Object.freeze():

The Object.freeze() method freezes an object for further use. We will not be able to change a frozen object. Once Object.freeze() is used on an object we will not be able to add a new property to it, we will not able to modify any existing property, or even delete a property.

Object.freeze() exmaple:

const obj = {
  property1: 50
};

Object.freeze(obj);
obj.property1 = 33; // It will not be changed
obj.property2 = 40; // It will not be added 
console.log(obj.property1); // 50


delete obj.property1; // cannot delete when freezed
console.log(obj); // {property1: 50}

Object.seal():

The Object.seal() method seals an object for further use. Once Object.seal() is used on an object we will not be able to add a new property to it, we will be able to modify any existing property but not delete a property.

Object.seal() example:

const obj = {
  property1: 50
};

Object.seal(obj);
obj.property1 = 33; // It will be changed
obj.property2 = 40; // It will not be added 
console.log(obj.property1); // 33


delete obj.property1; // cannot delete when sealed
console.log(obj); // {property1: 33}

Object.preventExtensions():

The Object.preventExtensions() method prevents an object for further extension. Once Object.prevents() is used on an object we will not be able to add a new property to it, but will be able to modify any existing property and will be able to delete a property.

The table shows the comparison of the above Object.freeze, Object.seal and Object.preventExtensions methods:

CREATEREADUPDATEDELETE
Object.freeze()xxx
Object.seal()xx
Object.preventExtensions()x
Reference: