Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Defining a getter in an object literal

Use `get` in an object literal to run a function when a property is read, so the value can reflect the object's current state without an explicit method call.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const obj = { get name() { /* body */ } };
const computed = { get [expression]() { /* body */ } };

An Object getter accessor definition uses get name() { … } in an object literal to create an own, enumerable, configurable accessor property. Use get [expression]() { … } for a computed key. The parameter list must be empty; otherwise the definition is a SyntaxError.

Reading obj.name calls the getter with no arguments and returns its result. In this read, this is obj, even when the getter is inherited. The result is not cached automatically. In contrast, name() { … } defines an ordinary method stored as a data property's value; reading that property does not call the method.

An accessor descriptor uses get and set, not value and writable. Use Object.getOwnPropertyDescriptor() to inspect an own property without running its getter. If there is no corresponding setter, ordinary assignment to the property is ignored in non-strict code and throws a TypeError in strict mode.

To add a getter to an existing object, use Object.defineProperty() with a descriptor containing get. For a new property, omitted enumerable and configurable flags then default to false, unlike in an object literal. A public non-static class getter lives on the class prototype and is non-enumerable.

Examples

{
  const item = {
    price: 10,
    quantity: 2,
    get total() {
      return this.price * this.quantity;
    },
  };

  console.log(item.total);
  item.quantity = 3;
  console.log(item.total);

  const descriptor = Object.getOwnPropertyDescriptor(item, "total");
  console.log(typeof descriptor.get);
  console.log(descriptor.enumerable);
  console.log(descriptor.configurable);
}

Result

20
30
function
true
true

The first read of `item.total` returns `20`; after `quantity` changes, the second returns `30`. The last three lines show that the descriptor contains a getter function and that the property is enumerable and configurable.

Related lessons

  • JavaScript · Lesson 19 · Advanced · Version: 4

Sources