AI Hints
Home›JavaScript Tutorial›Getters and Errors
JavaScript · Lesson 73 of 138

Getters and Static

Computed and shared.

⏱ 2 min read▶ Video at 1:28:51🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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 and Static
From the video: Getters and Static
  • 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.

app.jsjavascript
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);
Output
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.

keyvalue
get area()read as r.area
Always up to datecomputed each time
staticcalled on the class
ExamplesMath.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()
Next up: Errors and try/catch — handling problems