Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 156 ยท Objects

Property Descriptors and Object Protection

Control JavaScript properties with descriptors - writable, enumerable and configurable - and protect objects with freeze, seal, preventExtensions and deep freeze.

Every property on a JavaScript object is more than a name and a value. Behind the scenes, each one carries a small set of flags that decide whether it can be changed, whether it shows up in loops, and whether it can be deleted or redefined. Together, the value and these flags are called the property's descriptor.

Most of the time you never think about descriptors, because properties you create the normal way get the friendliest settings. But they explain a lot of everyday behavior: why Object.keys() skips some properties, why Math.PI = 3 does nothing, and how Object.freeze() actually works. In this lesson you'll read and write descriptors, then use them to protect objects at different strengths.

Reading a descriptor

Object.getOwnPropertyDescriptor(obj, key) returns the descriptor of one property. A normal data property has four fields:

JS What a descriptor looks like

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The three flags mean:

Flag When true When false
writable The value can be changed with = Assignments are ignored (or throw in strict mode)
enumerable Shows up in for...in, Object.keys(), spread and JSON.stringify() Hidden from those, but still readable by name
configurable Can be deleted, and its flags can be changed Can't be deleted; flags are locked (with one exception, below)

Properties created by assignment or in an object literal get true for all three. That's why you rarely notice them.

Defining properties with Object.defineProperty

Object.defineProperty(obj, key, descriptor) creates or changes a property with exactly the flags you choose. There's a trap here: any flag you leave out defaults to false when the property is new. That's the opposite of normal assignment.

JS defineProperty and its defaults

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The example starts with "use strict", so the failed write and delete throw a TypeError. Delete that line and run it again: in non-strict scripts, the same operations fail silently: no error, no change. That silent failure is one more reason to use strict mode, which modules and classes use automatically.

When you call defineProperty on a property that already exists, only the fields you pass change; the others keep their current values. So Object.defineProperty(book, "pages", { enumerable: false }) hides pages from loops while keeping it writable.

Several at once: defineProperties

Object.defineProperties(obj, { key: descriptor, ... }) defines many properties in one call. You can also pass descriptors as the second argument of Object.create(proto, descriptors).

Accessor properties

A descriptor can describe an accessor property instead of a data property. It has get and/or set functions in place of value and writable. You met these in Getters and Setters. A single descriptor can't mix the two kinds: passing both value and get throws a TypeError.

JavaScript
const temperature = { celsius: 21 };

Object.defineProperty(temperature, "fahrenheit", {
  get() { return this.celsius * 9 / 5 + 32; },
  set(f) { this.celsius = (f - 32) * 5 / 9; },
  enumerable: true,
});

Practical uses for descriptors

Most application code never calls defineProperty. It earns its place in a few specific situations:

  • Hidden metadata. Attach an internal property that shouldn't appear in JSON.stringify() or in loops over the object.
  • Constants on an object. A non-writable, non-configurable property can't be replaced by mistake.
  • Copying getters correctly. Spread and Object.assign() call getters and copy the result. To copy the getter itself, copy its descriptor.
JS Copying an object together with its getters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The pattern Object.defineProperties({}, Object.getOwnPropertyDescriptors(source)) is the standard way to clone an object's own properties exactly, flags and accessors included. It's still a shallow copy: items is shared until you replace it. (Copying Objects covers shallow and deep copies.)

Which properties count? Object.keys() lists own enumerable string keys. Object.getOwnPropertyNames() adds the non-enumerable ones, and Reflect.ownKeys() returns every own key, symbols included. for...in also walks enumerable properties inherited from the prototype.

The configurable flag in detail

configurable: false is a one-way door. Once a property is non-configurable, you can't delete it, can't turn it back to configurable, can't switch it between data and accessor, and can't change enumerable. There is exactly one change still allowed: a non-configurable property that is writable can be made non-writable (and its value can still be changed while it's writable). Going the other way, from writable: false back to true, is forbidden.

That rule is what makes Object.freeze() permanent: once frozen, nothing can unfreeze an object.

Three levels of object protection

The language gives you three built-in functions for locking down an entire object. Each is stronger than the last:

Add properties Delete properties Change values Change flags
Normal object Yes Yes Yes Yes
Object.preventExtensions(obj) No Yes Yes Yes
Object.seal(obj) No No Yes No
Object.freeze(obj) No No No No

Under the hood they're built from descriptors: seal() prevents extensions and sets every own property to configurable: false; freeze() does the same and also sets every data property to writable: false. Each has a matching check: Object.isExtensible(), Object.isSealed() and Object.isFrozen().

JS preventExtensions vs seal vs freeze

Press Run (or Ctrl + Enter) to see the console output here.

No output.

All three are irreversible and shallow. They work on the object's own properties only; a nested object or array inside is still a separate, fully mutable object. A frozen object holding an accessor property still runs its setter, too, because freezing only locks data properties.

When might you use each?

  • freeze() for constants, lookup tables and shared configuration that must never change, and for state objects in an immutable style.
  • seal() when an object's shape is fixed but its values may change, for example a settings object where typos in property names should fail loudly.
  • preventExtensions() rarely; mostly when you need the weakest form of shape locking.

Deep freeze

Because freeze() stops at the first level, protecting a nested structure needs a recursive helper. Freeze the children first, then the object itself:

JS A deepFreeze helper

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A few details make this helper robust. It reads descriptors instead of property values, so it doesn't trigger getters. It skips objects that are already frozen, which also stops infinite loops when an object refers to itself. And it uses Reflect.ownKeys() so symbol and non-enumerable keys are covered.

Be careful what you deep-freeze. Freezing a Map, Set or Date does not stop map.set(), set.add() or date.setFullYear(): their data lives in internal slots, not properties. And freezing an object you don't own (like one from a library) can break that library. Deep-freeze plain data you created yourself.

Performance and practice

Freezing is cheap, and modern engines handle frozen objects well. Still, deep-freezing large data on every update adds up. A common compromise is to deep-freeze state only in development, to catch accidental mutations early, and skip it in production builds.

Descriptors also matter to Proxy and Reflect, where traps such as defineProperty and getOwnPropertyDescriptor let you intercept these very operations.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After Object.defineProperty(obj, "code", { value: 5 }) on a new property, which is true?

    When defineProperty creates a property, every flag you omit defaults to false.
  2. 2. Which operation is still allowed on a sealed object?

    seal() blocks adding and deleting and locks the flags, but data properties stay writable.
  3. 3. const s = Object.freeze({ tags: ["a"] }); What does s.tags.push("b") do?

    freeze() only locks the object's own properties. The array it points to is a separate object that is still mutable.
  4. 4. Why does { ...source } lose getters?

    Spread reads each property, which runs the getter. Copy descriptors with Object.getOwnPropertyDescriptors() to keep accessors.
  5. 5. In non-strict code, what happens when you assign to a non-writable property?

    Sloppy mode ignores the write without an error. Strict mode, modules and classes throw a TypeError instead.

Summary

  • Each property has a descriptor: value + writable (data) or get/set (accessor), plus enumerable and configurable.
  • Object.defineProperty() sets flags precisely; omitted flags default to false for new properties.
  • Non-enumerable properties hide from Object.keys(), spread and JSON; non-configurable ones can't be deleted or reconfigured.
  • preventExtensions() < seal() < freeze(): each locks more, all are permanent and shallow.
  • A recursive deepFreeze() protects nested data; copy exact properties with getOwnPropertyDescriptors().

Next: Arrays โ€” ordered lists of values and how to work with them.