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:

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:

Exceptions:

We have a complete list of Javascript Object methods, to check those please go through this JavaScript Object Complete Reference article.

Supported Browsers: