Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Sealing JavaScript Objects Using Object.seal()

DZone's Guide to

Sealing JavaScript Objects Using Object.seal()

Hate when others mess your code? Learn how to seal objects in JavaScript, so new properties can't be added or existing ones can't b e re-configured.

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

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.

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:
web dev ,javascript ,objects

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}