Property descriptors

Every property of a JavaScript object has more than a value. It carries more than a value. A data property has a value and three flags: writable, enumerable and configurable, and an accessor property has a getter and a setter in place of the value. A literal sets all of them to a useful default, and Object.defineProperty sets each one by hand.

This lesson writes properties with that call, reads the descriptor back, defines a getter and a setter, and hides a key from the loops and from JSON. It is the same machinery behind Object.freeze, which the earlier lesson uses without showing the flags underneath.

defineProperty writes a property

Object.defineProperty takes the object, the key and a descriptor, which is an object with the flags. Every flag written here is the one a literal would give, so the property behaves like an ordinary field, and the call exists to show what a plain field really is. The descriptor read back is the same object with the same four fields, value included.

The file define.mjs:

const account = { owner: 'Ada' }; Object.defineProperty(account, 'balance', { value: 100, writable: true, enumerable: true, configurable: true, }); console.log('the value:', account.balance); console.log('the keys:', Object.keys(account).join(',')); console.log( 'the descriptor:', JSON.stringify(Object.getOwnPropertyDescriptor(account, 'balance')), );

node define.mjs

the value: 100
the keys: owner,balance
the descriptor: {"value":100,"writable":true,"enumerable":true,"configurable":true}

The property answers like any other, appears in the list of keys, and reports its three flags when asked. A descriptor is either a data descriptor, with a value and a writable flag, or an accessor descriptor, with a get and a set and no value at all, and the next two sections show the other kind.

What a descriptor defaults to

A descriptor that names only a value sets every other flag to false. The property is then invisible to Object.keys and to a loop, refuses every write, and cannot be redefined or deleted, which is a set of three locks that surprises anyone who expects the defaults of a literal. A module is strict code, so the refused write throws instead of being ignored.

The file defaults.mjs:

const hidden = {}; Object.defineProperty(hidden, 'token', { value: 'abc' }); const descriptor = Object.getOwnPropertyDescriptor(hidden, 'token'); console.log('value:', descriptor.value); console.log('writable:', descriptor.writable); console.log('enumerable:', descriptor.enumerable); console.log('configurable:', descriptor.configurable); console.log('the keys:', Object.keys(hidden).length); console.log('still in the object:', 'token' in hidden, hidden.token); try { hidden.token = 'other'; } catch (error) { console.log(error.name + ': ' + error.message); } try { Object.defineProperty(hidden, 'token', { value: 'other' }); } catch (error) { console.log(error.name + ': ' + error.message); } console.log('the value did not change:', hidden.token);

node defaults.mjs

value: abc
writable: false
enumerable: false
configurable: false
the keys: 0
still in the object: true abc
TypeError: Cannot assign to read only property 'token' of object '#<Object>'
TypeError: Cannot redefine property: token
the value did not change: abc

Three flags, all false, and the value is still there: the two lines before the errors read it without trouble. The first error is the write, and its text names the property and the object. The second is a redefine of a property that is not configurable, which no flag in the descriptor may change. A plain field has all three flags true, which is why the same lines on a literal do nothing unusual.

Getters and setters

A getter is a function that runs on every read of the key, and a setter is a function that runs on every write. The object below stores the temperature in celsius and offers fahrenheit as a computed view, so the two scales cannot drift apart. In a literal the two are written with the get and set keywords, and Object.defineProperty takes the same pair in a descriptor.

The file accessors.mjs:

const temperature = { celsius: 20, get fahrenheit() { return this.celsius * 9 / 5 + 32; }, set fahrenheit(value) { this.celsius = (value - 32) * 5 / 9; }, }; console.log('a getter reads like a field:', temperature.fahrenheit); temperature.fahrenheit = 212; console.log('a setter writes another field:', temperature.celsius); console.log('the getter again:', temperature.fahrenheit); console.log('the own keys:', Object.keys(temperature).join(',')); console.log( 'the descriptor has a get:', typeof Object.getOwnPropertyDescriptor(temperature, 'fahrenheit').get, );

node accessors.mjs

a getter reads like a field: 68
a setter writes another field: 100
the getter again: 212
the own keys: celsius,fahrenheit
the descriptor has a get: function

The read looks like a field and runs a function, and the write changed the celsius field rather than adding a fahrenheit one. The two conversions agree because there is one stored number behind them. A getter costs a call on every read, so it is the right tool for a small derivation and the wrong one for work that a field could do once.

A key that is not enumerable

The enumerable flag decides what counts as the contents of an object. Object.keys, Object.values, the spread and JSON.stringify all skip a key with the flag off, while a direct read and the in operator still find it. That is how a hidden piece of state can sit next to the data without being copied or serialised.

The file enumerable.mjs:

const settings = { theme: 'dark', zoom: 2 }; Object.defineProperty(settings, 'internal', { value: 'do not copy', enumerable: false, }); console.log('Object.keys:', Object.keys(settings).join(',')); console.log('JSON:', JSON.stringify(settings)); console.log('the spread copy:', JSON.stringify({ ...settings })); console.log('but it is still there:', settings.internal); console.log('and the in check finds it:', 'internal' in settings); console.log('names rather than keys:', Object.getOwnPropertyNames(settings).join(',')); const counters = { visible: 1 }; Object.defineProperty(counters, 'hidden', { value: 2, enumerable: false }); let sum = 0; for (const key in counters) { sum += counters[key]; } console.log('a for-in loop adds the visible only:', sum);

node enumerable.mjs

Object.keys: theme,zoom
JSON: {"theme":"dark","zoom":2}
the spread copy: {"theme":"dark","zoom":2}
but it is still there: do not copy
and the in check finds it: true
names rather than keys: theme,zoom,internal
a for-in loop adds the visible only: 1

The hidden key was left out of every copy and every report, and it was still readable by name. Object.getOwnPropertyNames is the call that lists it, because that one asks for names rather than for contents. The last line counts a loop over the same object and adds only the visible one, which is the practical difference between a field and a hidden field.

Exercises

  1. Define balance in define.mjs without the writable flag and print it after a write. What happens on the assignment?
  2. Read the descriptor of owner in define.mjs, which was written as a plain field. Which of the three flags differ from the one the call set, if any?
  3. Add a setter for celsius to accessors.mjs that refuses a value below zero. Which of the two properties then becomes the only way to write the temperature?
  4. Write the hidden key of enumerable.mjs with writable: true and change it before the copies are made. Does the copy now contain it?
  5. Freeze the settings object of enumerable.mjs with Object.freeze and read the descriptor of one key. Which of the four flags changed?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What are the four keys of a property descriptor?

    Answer

    value, writable, enumerable, configurable

    A data descriptor carries a value and the three flags, and an accessor descriptor swaps the value for a get and a set.

  2. What happens to the flags a descriptor does not name?

    Answer

    They are false

    defineProperty fills every missing flag with false, which is the opposite of a literal.

  3. Which call skips a property whose enumerable flag is false?

    Answer

    Object.keys

    The list of keys is the list of contents, so a hidden key is not in it, while names and reads still find it.

  4. What is a getter?

    Answer

    A function that runs on every read of the property

    The get replaces the stored value, and the property computes its answer on each read.

  5. What does this program print? const o = {}; Object.defineProperty(o, "a", { value: 1 }); console.log(o.a, Object.keys(o).length);

    Answer

    1 0

    The read finds the value, and the key is not enumerable because the descriptor did not say it was.

  6. What does this program print? const o = { a: 1 }; Object.defineProperty(o, "b", { value: 2, enumerable: true }); console.log(Object.keys(o).join(","));

    Answer

    a,b

    Both keys are enumerable now, and the order is the order in which they were added.

  7. What does this program print? const o = { n: 2, get double() { return this.n * 2; }, }; o.n = 5; console.log(o.double);

    Answer

    10

    The getter runs at the moment of the read, so it uses the value the field has then.

  8. What does this program print? const o = { a: 1 }; Object.freeze(o); console.log(Object.getOwnPropertyDescriptor(o, "a").writable);

    Answer

    false

    Freezing turns the writable and configurable flags of every own property off.

  9. What happens when this module runs? const o = {}; Object.defineProperty(o, "a", { value: 1 }); o.a = 2; console.log(o.a);

    Answer

    It throws a TypeError, because a is read only

    The flag defaults to false, and a module is strict code, so the write throws instead of being dropped.

  10. What happens when this module runs? const o = {}; Object.defineProperty(o, "a", { value: 1 }); Object.defineProperty(o, "a", { value: 2 });

    Answer

    It throws a TypeError, because a is not configurable

    A property that is not configurable may not be redefined, and a descriptor with a new value counts as a redefinition.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image