Getters & Setters in JavaScript
Getters/setters disguise function calls as property access: get area() { return this.w * this.h; } computes on read, set width(v) validates on write — callers use plain circle.area and circle.width = 5 while logic runs underneath. Defined in literals and classes with get/set syntax, or retrofitted via Object.defineProperty.
Power with restraint: hidden computation surprises (getters doing I/O), setters throwing on invalid values, and infinite recursion when accessors touch same-named backing fields (convention: _width). Use for validation, laziness, and compatibility shims — not gratuitous wrapping.
Compute on read
get area() derives values from state — callers read a property, implementations run code.
Validate on write
set width(v) { if (v <= 0) throw ...; this._w = v; } guards invariants at assignment.
Backing fields differ
Accessors must store elsewhere (_w) — reading this.width inside get width recurses forever.
Keep them cheap
Getters run per access — no I/O, no heavy loops behind innocent-looking property reads.
let rect = { w: 3, h: 4, get area() { return this.w * this.h; }};console.log(rect.area);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.