Learn JavaScript
❯ objects.getters_setters

Getters & Setters in JavaScript

$concept

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.

$how it works
1

Compute on read

get area() derives values from state — callers read a property, implementations run code.

2

Validate on write

set width(v) { if (v <= 0) throw ...; this._w = v; } guards invariants at assignment.

3

Backing fields differ

Accessors must store elsewhere (_w) — reading this.width inside get width recurses forever.

4

Keep them cheap

Getters run per access — no I/O, no heavy loops behind innocent-looking property reads.

$example
let rect = {
w: 3,
h: 4,
get area() { return this.w * this.h; }
};
console.log(rect.area);
Output
12
1area looks like data but runs the getter on access.
2this.w * this.h computes 12 from live state — always current, never stored.
3Callers stay simple while derivation lives in one place.
$use cases
Derived values (area, fullName) computed from live state
Validated assignment through throwing setters
Lazy initialization on first read
Compatibility shims preserving property APIs over new storage

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.