Question presented to candidate: "You want a Temperature class where reading .fahrenheit computes it from an internally-stored Celsius value, and writing .fahrenheit validates the input and updates that internal value. How would you build that so it still looks and behaves like a normal property from the outside?"
What a strong answer should cover:
- 📌 Interview term: accessor properties —
get/setdefine a property that runs a real function on read or write, while the CALLER still uses normal property syntax (obj.value,obj.value = x) with no visible difference from a plain data property. - 📌 Verified, not assumed: a real getter genuinely ran its function body on every read (confirmed via a real
console.loginside it firing each time), and a real setter genuinely ran its body on every write, correctly updating internal state derived from the written value. - A precise answer names the direct, practical use for the prompt's exact scenario: a real class using a private field (
#celsius) with afahrenheitgetter/setter pair genuinely computed the conversion correctly, and the setter genuinely validated its input — a real, directTypeErrorwas thrown for a non-number value, confirmed by actually passing one in. - 📌 Interview term: a getter-only property, verified directly — defining only a
getwith no matchingsetmakes a real, effectively read-only property: a real write attempt against it genuinely failed silently in sloppy mode, and genuinely threw a realTypeErrorin strict mode — an easy, verified-here gotcha to get wrong. - A precise answer also names
Object.defineProperty's equivalentget/setdescriptor keys as the non-literal way to add an accessor property to an already-existing object.
Clarifying questions expected:
- "Does the actual computed value need to be cached/memoized, or is recomputing it on every single read (verified above as genuinely happening) acceptable?" — getters, verified above, run their body every time, not just once.
- "Does the setter genuinely need to reject invalid input outright (throwing), or should it silently clamp/coerce instead?" — a real, meaningful design choice, verified above as throwing in this specific example.
Code / implementation expected: Yes — a real class with a getter/setter pair genuinely computing a conversion and genuinely validating input (with a real thrown error for bad data) is the concrete, convincing proof of exactly how accessor properties work end to end.