get / set

Properties computed on read (get) and handled on write (set).

On this page

Example

#
JavaScript
const student = {
  firstName: 'Emma',
  lastName: 'Clark',
  get fullName() {
    return `${this.firstName} ${this.lastName}`
  },
  set fullName(value) {
    const [first, last] = value.split(' ')
    this.firstName = first
    this.lastName = last
  }
}

console.log(student.fullName)
student.fullName = 'Mia Turner'
console.log(student.firstName)
Console
Emma Clark
Mia

Definition and usage

#

Getters and setters let you define a property that looks like a plain field from the outside, but calls a function behind the scenes. A getter (get) computes a value on every read, and a setter (set) reacts to an assignment.

A getter is great for a value calculated from other fields, for example fullName from a first and last name. A setter lets you check or transform the assigned value before it lands on the object.

The data is usually stored in a separate field (often with an underscore or a private #), because a setter that writes to the same property would call itself forever.

Syntax

#
Syntax
const obj = {
  get name() { … },
  set name(value) { … }
}

More examples

#
Validation in a class setter
JavaScript
class Player {
  #level = 1

  get level() {
    return this.#level
  }

  set level(value) {
    if (value < 1) throw new RangeError('Level must be positive')
    this.#level = value
  }
}

const player = new Player()
player.level = 5
console.log(player.level)

try {
  player.level = 0
} catch (error) {
  console.log(error.message)
}
Console
5
Level must be positive

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • A getter shouldn’t have side effects or run expensive calculations, because it looks like a plain field read.
  • Keep the data behind a setter in another field, such as a private #level, otherwise the setter will call itself.

Related entries

#

Spotted a mistake or missing an example? Write to us.