Hone

Lessons · JavaScript · getters, static and #private

Getters read like properties; static lives on the class

get area() computes a value that is read without parentheses. static square() belongs to the class itself, not to instances. #w is a field only the class body can touch.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A getter lets a computed value look like data, so callers never know it is worked out on the fly. A static method is the natural home for a factory like Rect.square(3). Private fields keep internals from becoming someone else's dependency.

How to think about it

Ask: is this a value of ONE object (getter or field), or something about the kind itself (static)? Should outside code be able to change it directly? If not, make it #private and expose a method.

Worked example

class Rect {
  #w; #h;
Private fields: only the class body can touch them.
  constructor(w, h) { this.#w = w; this.#h = h; }
  get area() { return this.#w * this.#h; }
A getter: computed, read without parentheses.
  static square(side) { return new Rect(side, side); }
On the class, not on instances.
}
const r = Rect.square(3);
Called on the class.
console.log(r.area, typeof r.square);
9 undefined

Your turn

Make perimeter readable as r.perimeter.

class Rect {
  constructor(w, h) { this.w = w; this.h = h; }
   perimeter() { return 2 * (this.w + this.h); }
}

The trap

Calling a getter with parentheses: r.area() tries to call the number 9 and throws 'r.area is not a function'.

Practise getters, static and #private on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.