Skip to content

Computed property names: dynamic object keys (ES2015)

  • How { [expression]: value } computes a key inside an object literal or class body.
  • The exact evaluation order and how keys are converted to strings or symbols.
  • Why a computed "__proto__" key behaves differently from obj["__proto__"] = value.
  • How to use computed keys safely with user-controlled keys.

TL;DR: put any expression in square brackets where a property name goes, and its value becomes the key: { [field]: value }. It works for data properties, methods, getters, setters and class members. Computed property names were added in ECMAScript 2015, alongside object shorthand.

Before ES2015, an object literal could only use fixed names. When the key lived in a variable, you created the object first and assigned with bracket notation afterwards, so the object could not be built in a single expression such as a return or a function argument.

Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The output shown under each sample was produced with Node.js 22.23.

const field = 'shippingAddress';
const value = '1 Main St';
// Before ES2015: create the object, then assign with bracket notation.
const oldPatch = {};
oldPatch[field] = value;
oldPatch['updated_' + field] = true;
// ES2015: compute the key inside the literal.
const patch = {
[field]: value,
[`updated_${field}`]: true,
};
console.log(patch);
console.log(JSON.stringify(patch) === JSON.stringify(oldPatch));

Output:

{ shippingAddress: '1 Main St', updated_shippingAddress: true }
true
// Fragment: where a computed key can appear
const obj = {
[keyExpr]: value, // data property
[methodKey]() {}, // method
get [getterKey]() {}, // getter (and set [setterKey](v) {})
*[Symbol.iterator]() {}, // generator method with a symbol key
};
class Model {
[fieldKey] = 1; // class field
static [staticKey]() {} // static method
}

The rules that matter in practice:

  • Order. Properties are defined left to right. For each one, the key expression is evaluated first, then the value.
  • Conversion. The key goes through the spec’s ToPropertyKey: a symbol stays a symbol, everything else is converted to a string. [42] becomes "42", [null] becomes "null", an array becomes its join(','), and a plain object becomes "[object Object]", which is almost always a bug.
  • Duplicates. If two definitions produce the same key, the last one wins. Since ES2015 duplicate names are legal even in strict mode.
  • Names. A method or getter defined with a computed key gets that key as its name.
  • Classes. In a class body, computed member names are evaluated once, when the class is defined, not each time an instance is created.
const log = [];
const key = (k) => { log.push(`key ${k}`); return k; };
const val = (v) => { log.push(`value ${v}`); return v; };
// Evaluation order: left to right, each key before its value.
const order = { [key('a')]: val(1), [key('b')]: val(2) };
console.log(log.join(', '));
// Keys go through ToPropertyKey: symbols stay symbols, everything else becomes a string.
const tag = Symbol('audit');
const keys = { [42]: 'number', [null]: 'null', [['x', 'y']]: 'array', [{}]: 'object', [tag]: 'symbol' };
console.log(Reflect.ownKeys(keys));
// Duplicate keys: the last definition wins, even if one is computed.
console.log({ status: 'open', ['sta' + 'tus']: 'closed' });
// A computed "__proto__" creates an ordinary own property; it does not set the prototype.
const viaColon = { __proto__: { inherited: true } };
const viaComputed = { ['__proto__']: { inherited: true } };
console.log(viaColon.inherited, Object.hasOwn(viaColon, '__proto__'));
console.log(viaComputed.inherited, Object.hasOwn(viaComputed, '__proto__'));
// Computed method, getter and well-known symbol.
const prefix = 'order';
const batch = {
ids: ['ord-1', 'ord-2'],
[`${prefix}Count`]() { return this.ids.length; },
get [`${prefix}Label`]() { return `${this.ids.length} orders`; },
*[Symbol.iterator]() { yield* this.ids; },
};
console.log(batch.orderCount(), batch.orderLabel, [...batch], batch.orderCount.name);
// In a class, computed member names are evaluated once, when the class is defined.
let counter = 0;
class Report {
[`field${++counter}`] = 'a';
[`method${++counter}`]() {}
}
new Report(); new Report();
console.log(counter, Object.keys(new Report()), Object.getOwnPropertyNames(Report.prototype));

Output:

key a, value 1, key b, value 2
[ '42', 'null', 'x,y', '[object Object]', Symbol(audit) ]
{ status: 'closed' }
true false
undefined true
2 2 orders [ 'ord-1', 'ord-2' ] orderCount
2 [ 'field1' ] [ 'constructor', 'method2' ]

The __proto__ lines show where computed keys change meaning. Only the non-computed __proto__: value sets the prototype; a computed ['__proto__'] defines an ordinary own property. Plain assignment obj['__proto__'] = value is different again: it calls the inherited __proto__ setter.

The OrdersPortal checkout form keeps its state in a reducer. The field/changed action updates whichever field the user edited, returning a new object in one expression with computed keys and object spread. Because the field name comes from the UI, only allow-listed names are accepted.

// checkout-form.mjs - OrdersPortal checkout form state with computed keys.
const EDITABLE_FIELDS = new Set(['email', 'shippingAddress', 'deliveryNote']);
function formReducer(state, action) {
switch (action.type) {
case 'field/changed': {
const { field, value } = action;
if (!EDITABLE_FIELDS.has(field)) return state; // allow-list user-controlled keys
return {
...state,
values: { ...state.values, [field]: value },
touched: { ...state.touched, [field]: true },
};
}
default:
return state;
}
}
let state = { values: {}, touched: {} };
state = formReducer(state, { type: 'field/changed', field: 'email', value: 'ada@example.test' });
state = formReducer(state, { type: 'field/changed', field: 'deliveryNote', value: 'Leave at door' });
state = formReducer(state, { type: 'field/changed', field: '__proto__', value: { isAdmin: true } });
console.log(state);
// Why the allow-list still matters: assignment and computed keys treat "__proto__" differently.
const untrustedKey = '__proto__';
const assigned = {};
assigned[untrustedKey] = { isAdmin: true }; // invokes the __proto__ setter
const defined = { [untrustedKey]: { isAdmin: true } }; // defines an own data property
console.log(assigned.isAdmin, defined.isAdmin, JSON.stringify(defined));

Output:

{
values: { email: 'ada@example.test', deliveryNote: 'Leave at door' },
touched: { email: true, deliveryNote: true }
}
true undefined {"__proto__":{"isAdmin":true}}

The computed form is safer than assignment, because it never changes a prototype. It still produces an object with an own __proto__ key that JSON.stringify sends to the server, where a naive merge function might copy it with assignment and cause prototype pollution. Validating keys at the boundary fixes both problems.

  • Using an object as a key. { [customer]: total } gives the key "[object Object]", and every customer overwrites the same property. Use a Map for object keys, or compute a string id.
  • Accepting arbitrary user keys. Keys such as __proto__, constructor or toString can confuse later code. Check them against an allow-list, or build the object with Object.create(null) or a Map.
  • Silent overwrites. Two computed keys that evaluate to the same string raise no error; the later one wins.
  • Expecting per-instance keys in classes. class A { [makeKey()] = 1 } calls makeKey() once when the class is defined. Set dynamic per-instance properties in the constructor.
Need Use
One or a few keys known only at run time, inside an expression computed property names
Keys from a list of pairs Object.fromEntries(pairs) (ES2019)
Arbitrary or object keys, frequent additions and deletions Map
Symbol-keyed protocol methods such as [Symbol.iterator] computed property names (the only literal syntax for symbol keys)
Fixed, known names a plain key: { status: 'open' }

Computed keys suit immutable updates, lookup tables keyed by constants ({ [OrderStatus.Paid]: 'Paid' }) and protocol methods. For large dictionaries built from data, Object.fromEntries or a Map reads better.

According to MDN’s browser compatibility data, computed property names in object literals are supported in Chrome 47, Edge 12, Firefox 34, Safari 8, Node.js 4.0.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported them. Computed names in class bodies follow class support; computed class fields need public class field support (ES2022). For ES5 targets, compilers create the object first and add computed keys afterwards, and they differ in how: Babel’s preset-env uses an Object.defineProperty helper (matching native semantics), while TypeScript 5.x with --target es5 emits plain assignment (_a[k] = 2), which does trigger the __proto__ setter. Checked with @babel/preset-env 8.0 targeting IE 11 and TypeScript 5.9 tsc --target es5.

1. In { [a()]: b(), [c()]: d() }, in what order do the functions run? a, b, c, d. Properties are processed left to right, and for each one the key expression is evaluated before the value.

2. What key does { [{ id: 1 }]: 'x' } produce? "[object Object]". Non-symbol keys are converted to strings, and a plain object’s default string form is "[object Object]". Use a Map when keys are objects.

3. Is { ['__proto__']: proto } the same as { __proto__: proto }? No. Only the non-computed colon form sets the prototype. The computed form creates an own property named __proto__ and leaves the prototype as Object.prototype.

4. Senior scenario: an API endpoint applies PATCH bodies with { ...order, [field]: value } where field comes from the request. What risks do you raise? Clients can set any property, including server-owned fields such as status or total, so the endpoint needs an allow-list or schema validator. The computed key will not pollute the prototype itself, but an own __proto__ property can reach later code that merges with assignment, so reject reserved names at the boundary and log rejected fields.

  • { [expr]: value } evaluates expr and uses the result, converted to a string unless it is a symbol, as the key.
  • Evaluation is left to right, key before value; duplicates silently keep the last value.
  • Class computed names are evaluated once, at class definition.
  • A computed "__proto__" is an ordinary own property; validate user-controlled keys anyway.