Sub topic 12
Property Descriptors: writable, enumerable, configurable
This chapter assumes you are comfortable with object literals, dot and bracket access, adding and deleting properties, enumeration with Object.keys and for...in, and the prototype chain covered in earlier chapters. You should also know the difference between strict mode and sloppy mode, because property attributes show up most often in how assignments fail.
Up to now a property has been a simple key-value pair. Internally, JavaScript stores more than that. Each property has a set of attributes: hidden flags that control whether the value can change, whether the property appears when you list keys, and whether the property can be deleted or redefined. An object that describes these attributes is called a property descriptor.
The Two Kinds of Descriptor
Every property is one of two kinds:
| Kind | Attributes | Used for |
|---|---|---|
| Data property | `value`, `writable`, `enumerable`, `configurable` | Ordinary stored values |
| Accessor property | `get`, `set`, `enumerable`, `configurable` | Values computed by functions |
This chapter covers data properties. Accessor properties have their own chapter, but they share enumerable and configurable, so everything said about those two attributes applies to them as well.
The three boolean attributes mean:
writable: whether assignment can changevalue.enumerable: whether the property shows up infor...in,Object.keys, spread,Object.assign, andJSON.stringify.configurable: whether the property can be deleted, and whether its attributes can be changed later.
Inspecting Attributes
Object.getOwnPropertyDescriptor(obj, key) returns the descriptor for one own property, or undefined if the object has no own property with that key. Object.getOwnPropertyDescriptors(obj) returns all of them at once.
const book = { title: "Dune" };
console.log(Object.getOwnPropertyDescriptor(book, "title"));
// { value: 'Dune', writable: true, enumerable: true, configurable: true }
console.log(Object.getOwnPropertyDescriptor(book, "toString"));
// undefined (toString is inherited, not own)
console.log(Object.getOwnPropertyDescriptor(Math, "PI"));
// { value: 3.141592653589793, writable: false, enumerable: false, configurable: false }
console.log(Object.getOwnPropertyDescriptor([1, 2, 3], "length"));
// { value: 3, writable: true, enumerable: false, configurable: false }Built-in objects show the attributes in use. Math.PI cannot be changed, listed, or deleted. An array's length can be assigned, but it never appears in Object.keys, and you cannot delete it.
Defining Properties with Explicit Attributes
Object.defineProperty(obj, key, descriptor) creates or modifies a property and returns the object. Object.defineProperties(obj, descriptors) does the same for several keys.
The most common mistake with these functions is the defaults. When you create a property with an ordinary assignment or a literal, all three flags are true. When you create a property with defineProperty, any attribute you leave out defaults to false (and value defaults to undefined).
const a = {};
a.x = 1;
Object.defineProperty(a, "y", { value: 2 });
console.log(Object.getOwnPropertyDescriptors(a));
// {
// x: { value: 1, writable: true, enumerable: true, configurable: true },
// y: { value: 2, writable: false, enumerable: false, configurable: false }
// }
console.log(Object.keys(a)); // [ 'x' ]
console.log(JSON.stringify(a)); // {"x":1}If you want a property that behaves like a normal one, spell out every flag:
const b = {};
Object.defineProperty(b, "z", {
value: 3,
writable: true,
enumerable: true,
configurable: true
});
console.log(Object.keys(b)); // [ 'z' ]writable: Blocking Assignment
When writable is false, assignment does not change the value. How it fails depends on the mode. In sloppy mode the assignment is silently ignored. In strict mode it throws a TypeError. Silent failure is a common source of bugs, which is one reason to write modules and classes in strict mode. Modules and class bodies are strict automatically.
"use strict";
const settings = {};
Object.defineProperty(settings, "version", {
value: "1.0",
enumerable: true
});
try {
settings.version = "2.0";
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(settings.version); // "1.0"Gotcha: read-only properties block assignment through the prototype chain
Assigning to a property the object does not own normally creates a new own property that shadows the inherited one. There is one exception. If the inherited property is a non-writable data property, the assignment fails as though the property were on the object itself. defineProperty is not affected, because it defines a property directly and does not go through assignment.
"use strict";
const base = {};
Object.defineProperty(base, "kind", { value: "base" });
const child = Object.create(base);
try {
child.kind = "child";
} catch (err) {
console.log("assignment failed:", err instanceof TypeError); // true
}
console.log(Object.hasOwn(child, "kind")); // false
Object.defineProperty(child, "kind", { value: "child", enumerable: true });
console.log(child.kind); // "child"writable: false is also shallow. If the value is an object, that object's own properties can still change. You cannot replace the reference, but you can mutate what it points to.
The flowchart below shows how an assignment obj.key = v is resolved for data properties.
enumerable: Hiding from Listings
A non-enumerable property still exists, can still be read, and still answers true to in and Object.hasOwn. It is only left out of the operations that list or copy "visible" properties. The table shows which operations respect the flag.
| Operation | Includes non-enumerable own properties? |
|---|---|
| `for...in`, `Object.keys`, `Object.values`, `Object.entries` | No |
| Spread `{ ...obj }`, `Object.assign` | No |
| `JSON.stringify` | No |
| `Object.getOwnPropertyNames` | Yes (string keys only) |
| `Reflect.ownKeys` | Yes (strings and symbols) |
| `structuredClone` | No |
const user = { name: "Lin" };
Object.defineProperty(user, "passwordHash", { value: "abc123", writable: true });
console.log(Object.keys(user)); // [ 'name' ]
console.log({ ...user }); // { name: 'Lin' }
console.log(JSON.stringify(user)); // {"name":"Lin"}
console.log(Object.getOwnPropertyNames(user)); // [ 'name', 'passwordHash' ]
console.log(user.passwordHash); // "abc123"This is how built-in methods stay out of your loops. Object.prototype.toString is non-enumerable, so for...in does not report it on every object.
Copying also drops the attributes themselves. Spread and Object.assign read values and write them as plain properties, so a non-writable source property becomes writable in the copy. To copy attributes as well, combine the two descriptor functions:
const source = {};
Object.defineProperty(source, "id", { value: 1, enumerable: true });
const plain = { ...source };
const exact = Object.defineProperties({}, Object.getOwnPropertyDescriptors(source));
console.log(Object.getOwnPropertyDescriptor(plain, "id").writable); // true
console.log(Object.getOwnPropertyDescriptor(exact, "id").writable); // falseconfigurable: Locking the Definition
configurable: false is the strongest attribute and the only one you mostly cannot undo. Once a property is non-configurable:
deletefails (silently in sloppy mode,TypeErrorin strict mode).enumerablecannot change.configurablecannot be set back totrue.- The property cannot be converted between a data property and an accessor property.
Two changes are still allowed. If the property is writable, its value can still change, by assignment or by defineProperty. You can also change writable from true to false, but not back. These rules allow one-way tightening and never loosening.
"use strict";
const obj = {};
Object.defineProperty(obj, "level", {
value: 1,
writable: true,
enumerable: true,
configurable: false
});
obj.level = 2; // allowed: writable
Object.defineProperty(obj, "level", { writable: false }); // allowed: tightening
const attempts = [
() => delete obj.level,
() => Object.defineProperty(obj, "level", { enumerable: false }),
() => Object.defineProperty(obj, "level", { writable: true }),
() => Object.defineProperty(obj, "level", { value: 3 })
];
for (const attempt of attempts) {
try {
attempt();
console.log("succeeded");
} catch (err) {
console.log("TypeError:", err instanceof TypeError);
}
}
// TypeError: true (printed four times)
console.log(obj.level); // 2Unlike assignment, Object.defineProperty throws a TypeError on an invalid change in both strict and sloppy mode. Redefining a non-configurable property with exactly the same attributes and value is allowed and does nothing.
Failure Modes at a Glance
| Mistake | Symptom | Fix |
|---|---|---|
| Leaving flags out of a new `defineProperty` | Property is read-only, hidden, and permanent | Spell out each flag you want `true` |
| Assigning to a read-only property in sloppy mode | Value silently unchanged | Use strict mode, or check `writable` |
| Shadowing an inherited read-only property | Assignment fails on the child | Use `defineProperty` on the child |
| Copying with spread or `Object.assign` | Attributes lost, hidden properties dropped | Use `getOwnPropertyDescriptors` with `defineProperties` |
| Setting `configurable: false` too early | Cannot fix the property later | Lock properties only after setup is done |
The next chapter uses the accessor form of descriptors to compute values with getters and setters. The chapter after it shows how Object.seal and Object.freeze apply configurable: false and writable: false to every property at once.
Exercise
You run const o = {}; Object.defineProperty(o, "n", { value: 5 }); in sloppy mode, then o.n = 10; delete o.n; console.log(o.n, Object.keys(o));. What is printed, and why?
Show answer
It prints 5 []. Because the property was created with defineProperty and no flags, writable, enumerable, and configurable all default to false. The assignment is silently ignored because n is not writable. The delete silently fails because n is not configurable. Object.keys returns an empty array because n is not enumerable.
Exercise
A property has { writable: true, enumerable: true, configurable: false }. Which of these succeed: (a) assigning a new value, (b) redefining it with writable: false, (c) then redefining it with writable: true, (d) redefining it with enumerable: false?
Show answer
(a) and (b) succeed. A non-configurable property can still change its value while it is writable, and writable can go from true to false. (c) fails because writable cannot go back from false to true on a non-configurable property. (d) fails because enumerable cannot change on a non-configurable property. Both failures throw a TypeError from Object.defineProperty in any mode.
Exercise
Write a function cloneExact(obj) that returns a new object with the same prototype as obj and the same own properties, including non-enumerable ones, symbol keys, and their attributes.
Show answer
function cloneExact(obj) { return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); } Object.getOwnPropertyDescriptors collects every own property, including symbol keys and non-enumerable ones, with full attributes. Object.create accepts the same descriptor map as its second argument. The copy is still shallow: object values are shared, not cloned.