Object.seal() in JavaScript

Aug 15, 2019

The Object.seal() function prevents adding, removing, or re-configuring properties on a JavaScript object.

const sealed = Object.seal({ answer: 42 });

sealed.answer = 43; // OK

// TypeError: Cannot delete property 'answer' of #<Object>
delete sealed.answer;

// TypeError: Cannot add property newProp, object is not extensible
sealed.newProp = 42;

// TypeError: Cannot redefine property: answer
Object.defineProperty(sealed, 'answer', { enumerable: false });

seal() is similar to the Object.freeze() function, with one key difference: you can still write to existing properties on a sealed object, but you cannot write to a frozen object.

const sealed = Object.seal({ answer: 42 });
const frozen = Object.freeze({ answer: 42 });

sealed.answer = 43; // ok
// TypeError: Cannot assign to read only property 'answer' of object '#<Object>'
frozen.answer = 43;

Like with freeze(), adding, removing, or re-configuring a property from a sealed object only throws an error in strict mode. Otherwise it fails silently.

The seal() function is also similar to the Object.preventExtensions() function. However, the preventExtensions() function only prevents adding new properties to an object, you can still delete properties or reconfigure existing properties.

When To Use seal()

The freeze() function is much more commonly used, the seal() function is rare in production. One potential use case for seal() is to protect the global object in Node.js.

Object.seal(global);

global.newProp = 42; // TypeError

Certain npm modules, like safe-buffer, intentionally modify existing global variables, but you might want to make sure that no other npm module unintentionally adds new global variables. Admittedly sealing global is uncommon in the Node.js community and certainly not an established best practice, but try it out - you might be surprised by the results.


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!