Skip to content

getter

A getter is a function bound to an object property that runs every time code reads that property, so the property’s value is computed on each read instead of stored.

A property with a getter is an accessor property rather than a data property. Instead of a stored value, it holds the getter function and, optionally, a setter function. Reading it calls the getter with this set to the object the read started from, and the read returns whatever the getter returns.

Most getters come from the get syntax in an object literal or a class body. Object.defineProperty() can also add one to an existing object. Built-in objects use getters too. The .size property of a Map is a getter on Map.prototype.

A class getter lives on the class’s prototype and is shared by every instance. Instances reach it through the prototype chain, and it isn’t enumerable. Code that copies an object’s own enumerable properties, such as JSON.stringify() or spread syntax, leaves it out.

Example

Say a shopping cart class computes its total from the item prices, and the app later saves the cart as JSON:

Language: JavaScript
> class Cart {
…   constructor(prices) {
…     this.prices = prices;
…   }
…   get total() {
…     return this.prices.reduce((sum, price) => sum + price, 0);
…   }
… }
undefined
> const cart = new Cart([12, 30]);
undefined

> cart.total
42
> cart.prices.push(8);
3
> cart.total
50

> Object.getOwnPropertyDescriptor(Cart.prototype, "total")
{
  get: [Function: get total],
  set: undefined,
  enumerable: false,
  configurable: true
}
> Object.hasOwn(cart, "total")
false

> JSON.stringify(cart)
'{"prices":[12,30,8]}'
> ({ ...cart })
{ prices: [ 12, 30, 8 ] }

Reading cart.total reruns the getter, so the total follows the updated prices. The property descriptor has a get function and no value, which marks total as an accessor property on Cart.prototype. Because the getter isn’t an own property of cart, the JSON text and the spread copy both lose the total. A property read searches the prototype chain, while copying looks only at own properties:

Reading cart.total walks from cart up to the getter on Cart.prototype, while JSON.stringify copies only the own prices property.
Getters Live on the Prototype, Not the Instance
A developer flips property switches beside a glass cabinet that locks a record card, with stations labeled WRITABLE, ENUMERABLE, FREEZE, SEAL, and SYMBOL.

Course

The JavaScript Object Model: Properties, Descriptors, and Freezing

Port a print shop's Python proof card export to JavaScript, and learn to control what an object owns, computes, lists, and lets you change, with descriptors, symbols, and freezing.

advanced js py

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Nov. 18, 2026