get / set
Properties computed on read (get) and handled on write (set).
Example
#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)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
#const obj = {
get name() { … },
set name(value) { … }
}More examples
#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)
}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
#- classDefines a class: a template for creating objects that share the same fields and methods.
- thisA keyword pointing to the object a function was called on.
- Object.freeze()Freezes an object, blocking the addition, removal, and change of its properties.
- #fieldFields and methods prefixed with # are private: only code inside the class can access them.
Spotted a mistake or missing an example? Write to us.