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 Crafter’s Git-based content management system is reinventing modern digital experiences.

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.

Crafter CMS is a modern Git-based platform for building innovative websites and content-rich digital experiences. Download this white paper now.

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 }}