Sealing JavaScript Objects with `Object.seal`

Sealing JavaScript Objects with `Object.seal`

The Object.seal() technique for JavaScript seals an article which keeps new properties from being added to it and denotes all current properties as non-configurable. The item to be fixed is passed as a contention, and the technique returns the article which has been fixed.

Let's walk through how it works.

var rectangle = {
    height: 5,
    width: 10
};

Object.seal(rectangle);

rectangle.depth = 15;

rectangle.width = 7;

console.log(rectangle);

As you can see before adding new properties object is sealed so output will be remains same but existing property can be modified

As well as forestalling the expansion of new properties, a fixed item can't have properties eliminated by means of delete. For instance:

delete rectangle.width;

// Outputs: {
//     height: 5,
//     width: 7
// }
console.log(rectangle);

Object.seal has one last impact. It makes all item properties non-configurable, keeping you from designing them into an alternate state with Object.defineProperty and comparable strategies.

Object.defineProperty(rectangle, "height", {
    writable: false
});

rectangle.height = 22;

// Outputs: 22
console.log(rectangle.height);

In this model, notwithstanding endeavoring to arrange the writability to bogus, the tallness property stays writable.

If you want detect any object is sealed or not then call

// Outputs: true console.log(Object.isSealed(rectangle));

Object.seal is part of the ECMAScript 5 specification, which means it isn't available in older browsers like IE8 and below.

Thank you