liveBook · Manning

Data descriptor

As explained in Secrets of the JavaScript Ninja, Third Edition

A data descriptor is a property descriptor that specifies a property's stored value and data-property attributes.

A data descriptor defines an object property with a stored value and controls such as writability, enumerability, and configurability. Use Object.defineProperty when direct assignment does not give you the property behavior you need. section 9.1.2

When defining a property with a data descriptor:

  • Provide a value; writable, enumerable, and configurable default to false. section 9.1.2
  • A non-writable property rejects assignment; in strict mode, that assignment throws an error. section 9.1.2
  • A non-configurable, non-writable property is effectively permanent. If writable is true but configurable is false, its value can change, but other aspects of its definition cannot. section 9.1.2
const obj = {};
Object.defineProperty(obj, "surfNinjaCount", {
  value: 3,
});

console.assert(
  obj.surfNinjaCount === 3,
  "There are 3 surf ninjas.",
);

A minimal Object.defineProperty call supplies a value for the new property. section 9.1.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines value and property attributes, explains their defaults and assignment restrictions, and describes permanence without broader descriptor internals.
Examples
Demonstrates defining surfNinjaCount with a value of 3.
What it assumes
Assumes familiarity with object properties and direct assignment; contrasts data descriptors with accessor descriptors.
What you can do after
Apply it via Object.defineProperty to create value properties with controlled writability, enumerability, and configurability.
How it connects
Connects Object.defineProperty, object properties, and accessor descriptors.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.