Accessor Properties With defineProperty

Define getter and setter descriptors with Object.defineProperty to validate writes and expose computed values without leaking internals.

JavascriptSecurity Boundaries

Code

javascriptsnippet
36 lines
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.50

How 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

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.