Expensive calculations
Compute a costly value only when code first needs it.
JS Puzzles · Const
A memoized getter computes a property value on first access and caches it for subsequent reads. It combines lazy evaluation with property-level memoization.
A memoized getter delays an expensive calculation until the property is first read, then replaces or stores the result so later reads reuse it. This is useful when the value is expensive, may never be needed, and remains stable after calculation.
get propertyName() { /* ... */ }The getter's returned value becomes the value observed through the property.
const object = {
get expensiveValue() {
delete this.expensiveValue;
return (this.expensiveValue = calculateValue());
},
};
function calculateValue() {
console.log("calculated");
return 42;
}
console.log(object.expensiveValue);
console.log(object.expensiveValue);The first access computes and replaces the getter with a data property; later accesses read the cached value.
Compute a costly value only when code first needs it.
Avoid loading or retrieving data that may never be used.
Reuse an immutable derived value across repeated property reads.
getsetterObject.defineProperty()Object.defineProperties()