JavaScript Object seal() Method (original) (raw)
Last Updated : 29 May, 2023
JavaScript Object.seal() method is used to seal an object. Sealing an object does not allow new properties to be added and marks all existing properties as non-configurable. Although values of present properties can be changed as long as they are writable. The object to be sealed is passed as an argument and the method returns the object which has been sealed.
Syntax:
Object.seal(obj)
Parameters:
- obj: It is the object which has to be sealed.
Return Value: Object.sealed() returns the object that was passed to the function.
Examples of the above function are provided below.
Example 1: In this example, the object “ob2” has been assigned properties of object “obj1” and it is been sealed so that new values cannot be added. The value of property 1 for obj2 has been updated since sealing an object allows existent properties to be changed.
Javascript
const obj1 = { property1:
'initial_data'
};
const obj2 = Object.seal(obj1);
obj2.property1 =
'new_data'
;
console.log(obj2.property1);
OUTPUT:
"new_data"
Example 2: In this example, the object “obj” has been assigned “prop: function” which has been later deleted since the object “obj wasn’t sealed. After that, a new object “o” has been assigned the sealed values of “obj” which prevented it from deletion but allowed updations in the existing properties.
Javascript
let obj = { prop:
function
() { }, name:
'adam'
};
console.log(obj);
obj.name =
'billy'
;
delete
obj.prop;
console.log(obj);
let o = Object.seal(obj);
delete
obj.prop;
console.log(obj);
obj.name =
'chris'
;
console.log(obj);
Output:
Object { prop: function () {}, name: "adam" } Object { name: "billy" } Object { name: "billy" } Object { name: "chris" }
Applications:
- Object.seal() is used for sealing objects and arrays, to make an object immutable.
Exceptions:
- It causes a TypeError if the argument passed is not an object.
- Deleting or adding properties to a sealed object will fail or throw a TypeError.
- Converting a data property to an accessor or vice versa will throw a TypeError.
We have a complete list of Javascript Object methods, to check those please go through this JavaScript Object Complete Reference article.
Supported Browsers:
- Google Chrome 6.0 and above
- Internet Explorer 9.0 and above
- Mozilla 4.0 and above
- Opera 12 and above
- Safari 5.0 and above
- Edge 12 and above