JS Built-ins
ObjectObject.definePropertybeginner

Object.defineProperty() β€” define a value property

πŸ“– Usage Example
// Define a property with a custom descriptor
const obj = {}
Object.defineProperty(obj, 'name', {
  value: 'Alice',
  writable: false,
  enumerable: true,
})

Use Object.defineProperty() to add or modify a property with precise control over its writability, enumerability, and configurability.

Object.defineProperty()

Object.defineProperty(obj, key, descriptor) defines a new property or modifies an existing one with precise control over its behaviour.

A data descriptor has value, writable, enumerable, and configurable.

Challenge: Implement addProperty(obj, key, val) that uses Object.defineProperty to add a writable, enumerable, configurable property.

const o = {}
addProperty(o, 'x', 42)
o.x // β†’ 42
πŸ’‘ Hints (2)
  • β€’ A data descriptor needs at least `value`. Add `writable:true, enumerable:true, configurable:true` to make it behave like a normal property.
  • β€’ Without `writable:true`, the property will be read-only.