Sub topic 1
Data Properties vs Accessor Properties
Every property on a JavaScript object belongs to one of two kinds. A data property stores a value. An accessor property stores no value. It holds a getter function that runs when you read the property and a setter function that runs when you assign to it. Both kinds look the same at the call site, since obj.x and obj.x = 1 work either way. They behave differently when you inspect, copy, or inherit them.
This chapter shows how to tell the two kinds apart with property descriptors, and how each kind behaves when you assign to it, copy it, or read it through the prototype chain. The later chapters on getters, setters, and private fields build on this.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript objects and property access with dot and bracket notation
- Functions and how
thisis bound when a method is called - ES2015
classsyntax andextends - The basics of prototypes and
Object.create - What
'use strict'changes, especially that silent failures become thrown errors
You can run every example in Node.js 16.9 or later (needed for Object.hasOwn) or in a browser console.
What a Property Descriptor Is
A property descriptor is a plain object that records how a single property behaves. The engine keeps these attributes internally. Object.getOwnPropertyDescriptor returns a copy of them so you can inspect them.
const book = { title: 'Dune' };
console.log(Object.getOwnPropertyDescriptor(book, 'title'));
// { value: 'Dune', writable: true, enumerable: true, configurable: true }That is a data descriptor. Here is an accessor property for comparison. The get syntax is covered fully in the next chapter. For now, look at the shape of the descriptor it produces.
const box = {
width: 2,
height: 3,
get area() {
return this.width * this.height;
}
};
const desc = Object.getOwnPropertyDescriptor(box, 'area');
console.log(desc);
// { get: [Function: get area], set: undefined, enumerable: true, configurable: true }
console.log('value' in desc); // false
console.log('writable' in desc); // false
console.log(box.area); // 6The accessor descriptor has get and set where the data descriptor had value and writable. No area value is stored anywhere. The getter computes 6 each time you read the property.
The Attributes
| Attribute | Data property | Accessor property | Meaning |
|---|---|---|---|
| `value` | yes | no | The stored value |
| `writable` | yes | no | Whether assignment can change `value` |
| `get` | no | yes | Function called on read, or `undefined` |
| `set` | no | yes | Function called on write, or `undefined` |
| `enumerable` | yes | yes | Whether the property shows up in `for...in`, `Object.keys`, spread, and `JSON.stringify` |
| `configurable` | yes | yes | Whether the property can be deleted, or have its attributes changed or its kind switched |
enumerable and configurable are shared. The other four split into two groups that cannot be mixed.
You Cannot Mix the Two Kinds
If a descriptor contains value or writable and also contains get or set, the engine rejects it:
try {
Object.defineProperty({}, 'x', {
value: 1,
get() { return 1; }
});
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message);
// Invalid property descriptor. Cannot both specify accessors and a value or writable attribute
}The exact message depends on the engine. The TypeError is guaranteed by the specification.
Inspecting Many Properties at Once
Object.getOwnPropertyDescriptors returns the descriptors of every own property, keyed by name. It is useful for debugging and, as shown later, for copying objects correctly.
const point = {
x: 1,
y: 2,
get length() {
return Math.hypot(this.x, this.y);
}
};
for (const [key, d] of Object.entries(Object.getOwnPropertyDescriptors(point))) {
const kind = 'value' in d ? 'data' : 'accessor';
console.log(key, kind);
}
// x data
// y data
// length accessorThe test 'value' in d is a reliable way to classify a descriptor. Data descriptors returned by the engine always include value, and accessor descriptors never do.
Built-ins Use Both Kinds
The standard library uses both kinds, so knowing which is which explains some behavior you may have seen.
console.log(Object.getOwnPropertyDescriptor([], 'length'));
// { value: 0, writable: true, enumerable: false, configurable: false }
const sizeDesc = Object.getOwnPropertyDescriptor(Map.prototype, 'size');
console.log(typeof sizeDesc.get, sizeDesc.set); // 'function' undefined
const protoDesc = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__');
console.log(typeof protoDesc.get, typeof protoDesc.set); // 'function' 'function'Array#length is a data property, although the engine gives it special behavior. Map#size is a getter with no setter, defined on Map.prototype rather than on each map. That is why new Map().size = 5 does nothing in sloppy mode and throws in strict mode. __proto__ is an accessor pair inherited from Object.prototype. It is not a real stored slot.
Default Attribute Values Depend on How You Create the Property
This is a common surprise. Properties created with an object literal or with plain assignment get true for every boolean attribute. Properties created with Object.defineProperty get false for every attribute you leave out.
const user = {};
user.name = 'Ada';
Object.defineProperty(user, 'id', { value: 7 });
console.log(Object.getOwnPropertyDescriptor(user, 'name'));
// { value: 'Ada', writable: true, enumerable: true, configurable: true }
console.log(Object.getOwnPropertyDescriptor(user, 'id'));
// { value: 7, writable: false, enumerable: false, configurable: false }
console.log(Object.keys(user)); // [ 'name' ]
console.log(JSON.stringify(user)); // '{"name":"Ada"}'id exists and can be read, but it is hidden from Object.keys and JSON, it cannot be reassigned, and it cannot be deleted. Accessors created with defineProperty follow the same rule: if you omit set, it defaults to undefined.
What Happens When You Assign
Reads are simple. A data property returns its value, and an accessor calls get with this set to the object you read from. If get is undefined, the read returns undefined.
Assignment has more cases, and those cases explain most of the confusing behavior. When you write obj.key = v, the engine looks for key on obj and then up the prototype chain, and acts on the first property it finds:
The two inherited cases are where data and accessor properties differ most. An inherited writable data property is shadowed: the assignment creates a new own property on the object and leaves the prototype's property alone. An inherited accessor is called: no own property is created.
'use strict';
const proto = {
kind: 'base',
get label() {
return `label:${this._label}`;
},
set label(v) {
this._label = v.toUpperCase();
}
};
const child = Object.create(proto);
child.kind = 'derived';
console.log(Object.hasOwn(child, 'kind')); // true (shadowed)
console.log(proto.kind); // 'base'
child.label = 'hello';
console.log(Object.hasOwn(child, 'label')); // false (setter ran instead)
console.log(Object.hasOwn(child, '_label')); // true (the setter wrote this)
console.log(child.label); // 'label:HELLO'This explains how class accessors work. Class getters and setters live on the prototype and are shared by every instance. Each instance's assignment runs the shared setter with this set to that instance.
A read-only data property on a prototype also blocks assignment on objects that inherit it, even though the assignment would otherwise create a new own property:
'use strict';
const frozenProto = Object.freeze({ kind: 'base' });
const obj = Object.create(frozenProto);
try {
obj.kind = 'derived';
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(Object.hasOwn(obj, 'kind')); // falseObject.defineProperty(obj, 'kind', { value: 'derived', writable: true, enumerable: true, configurable: true }) bypasses this check. It defines the own property directly and does not go through assignment.
Copying Turns Accessors into Data
Spread syntax, Object.assign, and JSON.stringify all read properties. Reading an accessor calls its getter, so these operations copy the getter's current result instead of the accessor itself.
const src = {
a: 1,
get double() {
return this.a * 2;
}
};
const copy = { ...src };
console.log(Object.getOwnPropertyDescriptor(copy, 'double'));
// { value: 2, writable: true, enumerable: true, configurable: true }
const clone = Object.defineProperties({}, Object.getOwnPropertyDescriptors(src));
clone.a = 5;
copy.a = 5;
console.log(clone.double); // 10 (still an accessor)
console.log(copy.double); // 2 (frozen snapshot)
console.log(JSON.stringify(src)); // '{"a":1,"double":2}'To copy an object with its accessors intact, pass its descriptors to Object.defineProperties or Object.create. Note that JSON.stringify includes double here only because it is an own, enumerable accessor. Accessors inherited from a class prototype are skipped. The pitfalls chapter covers that case.
Changing a Property's Kind
While a property is configurable: true, you can redefine it from one kind to the other. The old attributes are discarded and the new descriptor replaces them.
const settings = { theme: 'dark' };
Object.defineProperty(settings, 'theme', {
get() { return 'light'; },
enumerable: true,
configurable: true
});
console.log('value' in Object.getOwnPropertyDescriptor(settings, 'theme')); // false
console.log(settings.theme); // 'light'Once a property is configurable: false, it can no longer change kind, be deleted, or have enumerable changed. One exception remains: a non-configurable data property that is still writable can be changed to writable: false, though not back again. Object.freeze relies on this.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Expecting `defineProperty` defaults to be `true` | Property is hidden, read-only, and permanent | Set `writable`, `enumerable`, `configurable` explicitly |
| Putting `value` and `get` in one descriptor | `TypeError` | Choose one kind |
| Spreading an object to clone it | Getters become fixed values | Use `Object.getOwnPropertyDescriptors` |
| Checking `Object.hasOwn` after assigning through an inherited setter | Returns `false` | Expect the setter to store state elsewhere |
| Assigning to a getter-only property in sloppy mode | Silently ignored | Use strict mode or add a setter |
Exercise
You run const o = Object.create({ get x() { return 1; } }); o.x = 5; console.log(o.x, Object.hasOwn(o, 'x')); in sloppy mode. What is printed, and what changes in strict mode?
Show answer
It prints 1 false. The first property found for x is an inherited accessor with no setter, so the assignment fails without creating an own property. Sloppy mode ignores the failure. In strict mode the assignment throws a TypeError before the log runs.
Exercise
Write a function isAccessor(obj, key) that returns true only if key is an own accessor property of obj, and test it against { get a() { return 1; }, b: 2 }.
Show answer
function isAccessor(obj, key) { const d = Object.getOwnPropertyDescriptor(obj, key); return d !== undefined && !('value' in d); } returns true for 'a', false for 'b', and false for a missing key, because getOwnPropertyDescriptor returns undefined for properties that are not own properties.
Exercise
After const c = {}; Object.defineProperty(c, 'n', { value: 1 });, which of these succeed in strict mode: c.n = 2, delete c.n, Object.defineProperty(c, 'n', { get() { return 3; } })?
Show answer
None of them. With the defaults, n has writable false and configurable false. The assignment throws because the property is not writable, the delete throws because it is not configurable, and the redefinition as an accessor throws a TypeError because a non-configurable property cannot change kind.