Object.getOwnPropertyDescriptors(): copy getters (ES2017)
What you’ll learn
Section titled “What you’ll learn”- What
Object.getOwnPropertyDescriptors()returns. - Why
Object.assign()and spread break getters, and how descriptors fix it. - How to make a faithful shallow clone and an accessor-safe mixin.
- What descriptors cannot copy: private fields, internal slots, extensibility and nested data.
Summary
Section titled “Summary”TL;DR: Object.getOwnPropertyDescriptors(obj) returns an object that maps every own property key of obj, string and symbol, enumerable or not, to its descriptor (value/writable or get/set, plus enumerable and configurable). Pass that object to Object.defineProperties() or Object.create() to copy properties exactly as they are defined, instead of copying their current values.
It was added in ECMAScript 2017 and is supported by every current browser and runtime (details in Compatibility).
The problem it solves
Section titled “The problem it solves”Object.assign() and object spread copy values: they read each own enumerable property (running getters) and write plain data properties. An accessor becomes a snapshot of what it returned at copy time. The invented OrdersPortal app below has an order with a computed total.
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. All outputs shown were produced with Node.js 22.23.
// OrdersPortal: an order with a computed getter.const order = { items: [{ sku: 'A-77', cents: 1999, qty: 2 }], get totalCents() { return this.items.reduce((sum, i) => sum + i.cents * i.qty, 0); },};
// Object.assign (and spread) call the getter once and copy its result.const assigned = Object.assign({}, order);assigned.items = [{ sku: 'B-12', cents: 4500, qty: 1 }];console.log('assign:', assigned.totalCents); // stale 3998
// Before ES2017: loop over every own key and copy each descriptor.const manual = {};for (const key of Reflect.ownKeys(order)) { Object.defineProperty(manual, key, Object.getOwnPropertyDescriptor(order, key));}manual.items = [];console.log('manual loop:', manual.totalCents); // live getter: 0
// ES2017: one call returns every own descriptor.const copy = Object.defineProperties({}, Object.getOwnPropertyDescriptors(order));copy.items = [{ sku: 'B-12', cents: 4500, qty: 1 }];console.log('descriptors:', copy.totalCents); // live getter: 4500console.log(Object.getOwnPropertyDescriptors(order));Output:
assign: 3998manual loop: 0descriptors: 4500{ items: { value: [ [Object] ], writable: true, enumerable: true, configurable: true }, totalCents: { get: [Function: get totalCents], set: undefined, enumerable: true, configurable: true }}Every codebase used to write its own version of that loop. The ES2017 function returns exactly the shape that Object.defineProperties() and Object.create() accept, so a faithful copy is one expression.
How it works
Section titled “How it works”// Fragment: signatureconst descriptors = Object.getOwnPropertyDescriptors(obj);// { [key: string | symbol]: PropertyDescriptor }The spec algorithm runs ToObject(obj), then reads the descriptor of every key from [[OwnPropertyKeys]] (array indices, strings, then symbols) and stores it on a new plain object under the same key. So:
- Everything own is included: non-enumerable properties and symbol keys too, unlike
Object.keys()orObject.assign()(which copies symbols but skips non-enumerable properties). - Getters do not run. The descriptor holds the
getandsetfunctions themselves. - The result’s own properties are all enumerable, even when they describe non-enumerable properties, so
Object.keys(descriptors)lists hidden keys too. - It is shallow. A data descriptor’s
valueis the same reference as the original property. - Primitives are boxed (a string yields
'0','1', … andlength);nullandundefinedthrow aTypeError. - Proxies: a key reported by
ownKeyswhosegetOwnPropertyDescriptortrap returnsundefinedis left out.
const tag = Symbol('tag');const config = { region: 'us-east', [tag]: 'v2' };Object.defineProperty(config, 'auditRef', { value: 'audit:orders', enumerable: false });Object.freeze(config);
const descs = Object.getOwnPropertyDescriptors(config);console.log(Object.keys(descs), Object.getOwnPropertySymbols(descs));console.log(descs.auditRef);
// Clone with the same prototype, attributes and symbols. Each property keeps its// attributes, but the clone is extensible again: extensibility is not a property attribute.const clone = Object.create(Object.getPrototypeOf(config), descs);console.log(Object.isFrozen(clone), Object.isExtensible(clone));clone.extra = 1;console.log(Object.keys(clone));// .mjs files run in strict mode, so writing a non-writable property throws.try { clone.region = 'eu-west';} catch (error) { console.log(error.constructor.name);}console.log(clone.region);
const withNested = { address: { city: 'Springfield' } };console.log(Object.getOwnPropertyDescriptors(withNested).address.value === withNested.address); // shallowOutput:
[ 'region', 'auditRef' ] [ Symbol(tag) ]{ value: 'audit:orders', writable: false, enumerable: false, configurable: false}false true[ 'region', 'extra' ]TypeErrorus-easttrueObject.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)) is the standard faithful shallow clone: same prototype, keys, attributes and live accessors. Reapply Object.freeze(), seal() or preventExtensions() if the clone must match the source’s integrity level.
In TypeScript (lib.es2017.object.d.ts), the return type is { [P in keyof T]: TypedPropertyDescriptor<T[P]> } & { [x: string]: PropertyDescriptor }, so known keys get typed descriptors.
Realistic example
Section titled “Realistic example”OrdersPortal shares an Auditable behavior between several classes. It has a lazy getter that creates a per-instance audit trail. Mixing it in with Object.assign() runs that getter once, on the mixin object itself, and stores the resulting single array on the prototype, so every order shares one audit trail. Copying descriptors keeps the getter a getter.
// OrdersPortal: a reusable mixin whose accessors must survive being mixed in.const Auditable = { get auditTrail() { return (this._audit ??= []); }, record(event) { this.auditTrail.push({ event, at: '2026-11-18T10:00:00Z' }); return this; },};
function mixin(target, ...sources) { for (const source of sources) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } return target;}
class Order { constructor(id) { this.id = id; }}mixin(Order.prototype, Auditable);
const order = new Order('o-1001').record('created').record('paid');console.log(order.auditTrail.map((e) => e.event));console.log(typeof Object.getOwnPropertyDescriptor(Order.prototype, 'auditTrail').get);
// The same mix-in with Object.assign runs the getter once, on the mixin object itself,// and stores that single array on the prototype: every order would share it.class BrokenOrder {}Object.assign(BrokenOrder.prototype, Auditable);const a = new BrokenOrder().record('created');const b = new BrokenOrder();console.log(b.auditTrail.length, a.auditTrail === b.auditTrail);Output:
[ 'created', 'paid' ]function1 trueb never recorded anything, yet its trail has one entry: the shared-state bug that descriptor copying avoids. One difference from class syntax remains: record stays enumerable on Order.prototype, unlike class-body methods. Set enumerable: false on the copied descriptors if for...in output matters.
Common mistakes
Section titled “Common mistakes”-
Expecting a deep copy. Nested objects are shared. Use
structuredClone()for deep copies of plain data (it drops accessors and prototypes, so it solves a different problem). -
Cloning class instances that have private fields.
#fieldsare not properties, so the clone lacks them, and any method or getter that touches them throws.class Invoice {#number;constructor(number) { this.#number = number; this.status = 'open'; }get number() { return this.#number; }}const original = new Invoice('INV-7');const clone = Object.create(Object.getPrototypeOf(original), Object.getOwnPropertyDescriptors(original));console.log(clone instanceof Invoice, clone.status);try {console.log(clone.number);} catch (error) {console.log(error.constructor.name, '-', error.message);}Output:
true open, thenTypeError - Cannot read private member #number from an object whose class did not declare it. Built-ins with internal slots fail the same way: a descriptor clone of aDatethrowsTypeError: this is not a Date object.fromgetTime(). Give such classes their ownclone()method. -
Assuming the clone is frozen because the source was. Property attributes carry over; the object’s extensible flag does not.
When to use it and when not to
Section titled “When to use it and when not to”| Goal | Use |
|---|---|
| Copy enumerable data properties | { ...obj } or Object.assign() |
| Copy getters, setters, symbols, attributes and prototype (shallow) | Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)) |
| Mix accessors into a prototype | Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) |
Deep copy of plain data, Map, Date and so on |
structuredClone(obj) |
| Inspect one property | Object.getOwnPropertyDescriptor(obj, key) |
| Inspect accessors without running them | Object.getOwnPropertyDescriptors(obj) |
Use it in library code that must preserve how properties are defined: mixins, decorators and faithful clones. For plain data, prefer spread.
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, Object.getOwnPropertyDescriptors() is supported in Chrome 54, Edge 15, Firefox 50, Safari 10 (including iOS), Node.js 7.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported it. In TypeScript, the lib must include es2017 if your project pins an older one; core-js provides a polyfill for old runtimes.
Interview questions
Section titled “Interview questions”1. Why does Object.assign({}, objWithGetter) not copy the getter?
Object.assign uses [[Get]] on the source and [[Set]] on the target, so the getter runs and its result is written as a data property. Copying the accessor itself needs its descriptor.
2. How do you make a shallow copy that keeps the prototype, symbols, non-enumerable properties and accessors?
Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)). Then reapply freeze, seal or preventExtensions if the source had them.
3. Senior scenario: a team copies model objects with this descriptor clone to implement undo, and some objects start throwing TypeErrors. What happened and what do you recommend?
The models gained private fields or wrap built-ins with internal slots (Date, Map). Descriptor copies include only properties, so methods touching #fields or slots throw on the clone. Give each model an explicit clone() that goes through its constructor, or store undo snapshots as plain data with structuredClone() and rebuild models from them. Reserve descriptor copying for plain objects and mixins.
Key takeaways
Section titled “Key takeaways”Object.getOwnPropertyDescriptors()(ES2017) returns descriptors for every own key, including symbols and non-enumerable ones.- Combine it with
Object.defineProperties()orObject.create()to copy accessors and attributes thatObject.assignand spread flatten into values. - The copy is shallow, does not carry extensibility, and cannot include private fields or internal slots.
Related pages
Section titled “Related pages”- Object.assign(): value copying, and why it flattens accessors.
- Rest/spread properties:
{ ...obj }, which copies values the same way. - Object.keys() and Object.entries(): enumerable string keys only.
- Private class fields: why class instances are hard to clone.
- Reflect API and Proxy:
ownKeysand descriptor traps. - JavaScript interview questions
Official references
Section titled “Official references”- ECMAScript Language Specification,
Object.getOwnPropertyDescriptors ( O )(current draft; first published in ECMAScript 2017) - TC39 proposal: Object.getOwnPropertyDescriptors
- MDN: Object.getOwnPropertyDescriptors()
- MDN: Object.defineProperty() (descriptor attributes)
- MDN: structuredClone()
- TypeScript 6.0.3:
lib.es2017.object.d.ts