Accessor Properties With defineProperty
Define getter and setter descriptors with Object.defineProperty to validate writes and expose computed values without leaking internals.
Code
function createAccount(initial) {
let balance = initial;
const account = { id: 'acct-1' };
Object.defineProperty(account, 'balance', {
enumerable: true,
get() {
return balance;
},
set(value) {
if (!Number.isFinite(value) || value < 0) {
throw new RangeError('balance must be a non-negative number');
}
balance = value;
},
});
Object.defineProperty(account, 'formatted', {
get() {
return '$' + balance.toFixed(2);
},
});
return account;
}
const account = createAccount(10);
account.balance = 25.5;
console.log('balance:', account.balance, '| formatted:', account.formatted);
try {
account.balance = -1;
} catch (error) {
console.log('rejected:', error.message);
}
console.log('still:', account.formatted);Output
Captured from a sandboxed run of this snippet in the build pipeline.
balance: 25.5 | formatted: $25.50
rejected: balance must be a non-negative number
still: $25.50How the snippet works
Count the function createAccount as the entire surface area of Accessor Properties With defineProperty.
RangeError is the guard’s signal — thrown at the branch, before any partial work happens.
Applying it
The primary signature is function createAccount(initial)
Running the file prints labeled results such as balance:, rejected:, still: — each operation’s effect is visible in the output.
Statements that matter
throw new RangeError('balance must be a non-negative number');
return '$' + balance.toFixed(2);
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- What does the snippet do with malformed data?
- `RangeError` is raised at the guard, so invalid state never reaches the main logic.
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `createAccount` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.