Search⌘ K

Getters and Setters

Explore how getters and setters work in ES6 classes to create computed properties. Learn to sync values, hide information, and improve debugging by coupling logic with property access in JavaScript.

We'll cover the following...

Getters and setters are used to create computed properties.

Node.js
class Square {
constructor( width ) { this.width = width; }
get area() {
console.log('get area');
return this.width * this.width;
}
}
let square = new Square( 5 );
console.log(square.area)

Note that area only has a getter. Setting area does not change anything, as area is a computed property that depends on the width of the square.

For the sake of demonstrating ...