Getters and Static
Computed and shared.
Two more class features you'll meet often. Getters look like properties, but they're computed when you read them. And static methods belong to the class itself, not to each object.

- Getters: computed properties
- Static: belong to the class
- Both common
get and static
Area is a getter, so we read it like a property, with no brackets, and it's worked out from the width and height each time. Square is static, so we call it on the class itself. It's a handy way to make special kinds of rectangles. Run it.
class Rectangle {
constructor(w, h) { this.w = w; this.h = h; }
get area() { return this.w * this.h; }
static square(size) { return new Rectangle(size, size); }
}
const r = new Rectangle(3, 4);
console.log(r.area);
r.w = 10;
console.log(r.area);
console.log(Rectangle.square(5).area);12 40 25
Where you have seen these
You've used static methods already. Math dot max, Object dot keys, and Array dot is array are all static methods. And a string's length behaves like a getter. Getters are great for values that are always computed from other data, so they can never get out of date.
| key | value |
|---|---|
| get area() | read as r.area |
| Always up to date | computed each time |
| static | called on the class |
| Examples | Math.max, Object.keys |
Summary
Getters compute a property when you read it, and static methods belong to the class. Next, handling errors with try and catch.
Key takeaways- get name() { }
- static method() { }
- Class.method()