Sealing JavaScript Objects using Object.seal()

JavaScript provides a method Object.seal() which seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. Values of existing properties can still be changed if they are writable.

Let’s see an example:

var employee = {

name: "John Doe",

role: "Developer"

};

Object.seal(employee);

(function() {

"use strict";

employee.role = "Tester"

// TypeError: Can't define property department, object is not extensible

employee.department = "IT";

})();

The result would be as follows:

Screen Shot 2017-04-16 at 22.01.42

As you notice in the example above, we can modify the value of the existing property “role”. But we cannot add a new property “department”.

Let’s see another example:

var employee = {

name: "John Doe",

role: "Developer"

};

Object.seal(employee);

(function() {

"use strict";

//TypeError: Can't delete property name as it is non-configurable

delete employee.name;

})();

And the result would be as follows:

Screen Shot 2017-04-16 at 22.11.11

In the example above, we cannot delete the property name as it is non-configurable.

Fortunately, we have a method Object.isSealed to detect whether the object is sealed.

var employee = {

name: "John Doe",

role: "Developer"

};

Object.seal(employee);

if (Object.isSealed(employee)) {

alert("Employee is sealed!");

}

The output would be as follows:

Screen Shot 2017-04-16 at 22.28.29

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

One thought on “Sealing JavaScript Objects using Object.seal()

Comments are closed.