Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Object.defineProperty defaults in JavaScript

71 defineProperty defaults to false three times

fair

Add one property by assignment and one with Object.defineProperty and no attributes. Read both descriptors and account for every difference. Then show what the defaults cost: writing, deleting, redefining, Object.keys and JSON.stringify. Finish with a partial redefinition of an existing property.

Stuck? Three hints, smallest first
  1. 1. An assignment creates a property that is writable, enumerable and configurable. defineProperty defaults every one of those to false.
  2. 2. Not enumerable means Object.keys, for...in, spread and JSON.stringify all skip it.
  3. 3. Redefining an existing property only changes the attributes you name.

The answer

const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };
const flags = (obj, key) => {
  const d = Object.getOwnPropertyDescriptor(obj, key);
  return [d.writable, d.enumerable, d.configurable];
};

const order = {};
order.customer = 'Bisi';                                   // by assignment
Object.defineProperty(order, 'ref', { value: 'LAG-0071' }); // by descriptor, no attributes

const byAssignment = flags(order, 'customer');
const byDescriptor = flags(order, 'ref');

const visible = [Object.keys(order), JSON.stringify(order), { ...order }];
const enumerated = [];
for (const key in order) enumerated.push(key);

const readsFine = order.ref;
const foundAnyway = ['ref' in order, Object.getOwnPropertyNames(order), Object.hasOwn(order, 'ref')];

const writeRefused = attemptName(() => { order.ref = 'LAG-9999'; });
const deleteRefused = attemptName(() => { delete order.ref; });
const redefineRefused = attemptName(() => Object.defineProperty(order, 'ref', { value: 'LAG-9999' }));
const unchanged = order.ref;

// Redefining an existing property: unnamed attributes are left as they were.
Object.defineProperty(order, 'customer', { enumerable: false });
const afterPartial = flags(order, 'customer');
order.customer = 'Adaeze';                                  // still writable
const stillWritable = order.customer;
const nowHidden = Object.keys(order);

console.log('assignment vs descriptor:', byAssignment, byDescriptor);
console.log('visible                 :', visible);
console.log('refusals                :', [writeRefused, deleteRefused, redefineRefused]);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('an assignment gives writable, enumerable and configurable', byAssignment, [true, true, true]);
test('defineProperty with no attributes gives none of the three', byDescriptor, [false, false, false]);
test('so keys, JSON and spread all skip it, and for...in too', [visible, enumerated], [[['customer'], '{"customer":"Bisi"}', { customer: 'Bisi' }], ['customer']]);
test('it is still readable, and the own-property checks all find it', [readsFine, foundAnyway], ['LAG-0071', [true, ['customer', 'ref'], true]]);
test('writing, deleting and redefining it all throw in strict mode', [writeRefused, deleteRefused, redefineRefused], ['TypeError', 'TypeError', 'TypeError']);
test('and the value is exactly what it was', unchanged, 'LAG-0071');
test('redefining an existing property leaves unnamed attributes alone', afterPartial, [true, false, true]);
test('so the customer is hidden from keys but still writable', [stillWritable, nowHidden], ['Adaeze', []]);

Object.defineProperty is the low-level operation, and low-level here means "assume nothing". A descriptor is not a patch over sensible defaults — every attribute you omit is false, so { value: x } produces a property that is read-only, invisible and permanent. That is almost never what someone means the first time they use it, and the resulting bug is a value that silently refuses to change.

Silently is the wrong word inside a module, a class body or one of these panels, because those are all strict, and a refused write is a TypeError. In sloppy mode the same assignment does nothing at all and returns the value you assigned, so order.ref = 'x' evaluates to 'x' while order.ref is unchanged — the version of this bug that takes an afternoon to find.

The last two assertions are the rule that saves you. For a property that already exists, only the attributes you name are touched, so { enumerable: false } hides a key without making it read-only. That is how you keep a field out of JSON.stringify and Object.keys while ordinary code carries on assigning to it — cheaper than a symbol key and visible to getOwnPropertyNames when you are debugging.

Note which checks still find a non-enumerable property: in, Object.hasOwn, getOwnPropertyNames and Reflect.ownKeys. Enumerability governs listing and copying, not existence.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.