JavaScript Object.defineProperty() and defineProperties()
Quick answer
Object.defineProperty creates or updates a property using explicit descriptor fields instead of ordinary assignment semantics.
How it works
For a new data property, omitted writable, enumerable and configurable default to false. Updating an existing property can omit unchanged fields. A descriptor cannot mix get or set with value or writable. Object.defineProperties accepts a mapping of keys to descriptors. Both APIs return the target object and throw when a requested definition violates constraints.
const o = {}; Object.defineProperty(o,"id",{value: 7});const d = Object.getOwnPropertyDescriptor(o,"id");console.log(d.writable,d.enumerable,d.configurable);Expected output in Node.js:
false false falseA new descriptor defaults omitted boolean flags to false.
const o = {}; Object.defineProperties(o,{a:{value:2,enumerable:true},b:{value:5,enumerable:true}});console.log(o.a + o.b,Object.keys(o).join(","));Expected output in Node.js:
7 a,bBoth explicitly enumerable properties are defined.
Common mistakes
Do not assume descriptor defaults match object literal defaults.
Practice
Define a readable ID that does not appear in Object.keys and inspect its flags.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Object.defineProperty() and defineProperties() — Knowledge Check
Apply the taught concept and predict the output.
What is the default writable flag for a newly defined data property?
Which combination is invalid in a descriptor?
What does Object.defineProperty return on success?
What is the exact console output in JavaScript Object.defineProperty() and defineProperties() example 1?
const o = {}; Object.defineProperty(o,"id",{value: 7});const d = Object.getOwnPropertyDescriptor(o,"id");console.log(d.writable,d.enumerable,d.configurable);What is the exact console output in JavaScript Object.defineProperty() and defineProperties() example 2?
const o = {}; Object.defineProperties(o,{a:{value:2,enumerable:true},b:{value:5,enumerable:true}});console.log(o.a + o.b,Object.keys(o).join(","));