Open In App

What is the difference between freeze and seal in JavaScript?

Last Updated : 25 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, Object.freeze makes an object immutable, preventing any changes to existing properties and values. Object.seal allows changes to existing properties but prevents adding or removing properties. Both methods enforce strict immutability, but freeze is stricter than seal.

Object.seal()

Object.seal() is another method in JavaScript that prevents new properties from being added to an object and marks all existing properties as non-configurable Unlike Object.freeze(), Object.seal() allows the values of properties to be changed if they are writable. However, it prevents the addition or deletion of properties.

Syntax:

Object.seal(objectname);

Example: To demonstrate creating a non-extensible object using Object. seal() that does not prevent the value of the object from being changed.

javascript
// creates an object
let obj = {
    // assigns 10 to value
    value: 10
};
// creates a non-extensible object
Object.seal(obj);
// the value gets updated to 20
obj.value = 20;
console.log(obj.value);

Output
20

Object.freeze()

Object.freeze() is a method in JavaScript that prevents modification of existing property attributes and values of an object. When applied to an object, Object.freeze() makes its properties immutable, meaning they cannot be added, removed, or modified. Attempts to change the object or any of its properties (such as assigning new values or deleting properties) will fail silently or throw an error in strict mode.

Syntax:

Object.freeze(obj)

Example: This example, depicts how Object.freeze() is used to create a non-extensible object, but where the existing value of the object is prevented from being changed and 10 is given as the output.

javascript
let obj = {
    // assigns 10 to value
    value: 10
};
// creates a non-extensible object
Object.freeze(obj);
// updates the value
obj.value = 20;
// but cannot change the existing value
console.log(obj.value);

Output
10

Differences in a tabular form

freeze

seal

It is used to prevent the object from adding new propertiesIt is used to make the properties of an object non-configurable.
It is also used so that the current existing properties should not be modifiedIt is also used so that the new properties do not get added
It takes a parameter as an objectIt takes parameters as an object
Its return type is of the object type.Its return type is e-sealed object type.


Next Article

Similar Reads