Property descriptors — writable, enumerable, configurable¶
Level: 301 · for anyone who has wondered why some properties never show up in Object.keys
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: Every data property carries three flags; assignment sets all three to true, but Object.defineProperty defaults each to false, so the property it creates is hidden from Object.keys and JSON.stringify, and writing to it throws in a module and silently does nothing in sloppy code.
Keywords: Object.defineProperty, Object.getOwnPropertyDescriptor, writable, enumerable, configurable
What the finished page will answer¶
- What does
Object.getOwnPropertyDescriptorreturn for a property made by assignment, byObject.definePropertywith only avalue, and by a getter? - What does a write to a non-writable property do in an ES module, and in a sloppy
.cjsscript? - Once
configurableisfalse, which changes are still allowed: the value,writablefromtruetofalse, back again,enumerable,delete? - Which built-in properties are non-enumerable, and why does
for...inover an array never listlength? - How do
Object.getOwnPropertyDescriptorsandObject.definePropertiescopy an object with its getters intact, where spread keeps only values?
Examples it will need¶
-
property_descriptors_defaults_js.js— the descriptor of a property made by assignment beside one made by defineProperty with only a value, and how each shows in Object.keys and JSON.stringify -
property_descriptors_strict_write_sh.sh— a write to a non-writable property run as a module (TypeError, exit status 1) and as a sloppy .cjs script (no error, value unchanged) -
property_descriptors_copy_accessors_js.js— an object with a getter copied by spread and by defineProperties with getOwnPropertyDescriptors, showing which copy still computes
See also¶
freeze,sealandpreventExtensions— the three locks built from these flags- Getters and setters — accessor properties, which have get and set instead of value
- Strict mode — why a refused write throws in one mode only
- Own and inherited properties — the enumerable flag that for...in obeys