Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Computed property key in an object literal

Use `[expression]: value` to choose a property key when an object is created. The resulting key is a string or a symbol.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const obj = { [keyExpression]: valueExpression };
const withMethod = { [keyExpression]() {} };

An Object computed property key is a key derived from an expression inside brackets in an object literal. In { [key]: value }, JavaScript uses the value of key to determine the key; in { key: value }, the key is literally "key". Brackets can also name a method: { [key]() {} }. Outside the literal, obj[key] is property access, not a literal definition.

Each time the literal is evaluated, its definitions are processed from left to right. For [key]: value, JavaScript evaluates and converts the key before evaluating the value. Changing the variable key afterward does not rename the property. If key evaluation or conversion throws, the value expression is not evaluated.

ToPropertyKey first converts the result to a primitive with a string preference. It keeps a Symbol unchanged and converts other primitives to strings. Thus [1] and "1" name the same key. If two data property definitions produce the same key, the later one wins. To read a symbol-keyed property, use the same symbol, not a new symbol with the same description.

{ ["__proto__"]: null } creates an own data property and leaves the prototype unchanged. { __proto__: null } and { "__proto__": null } instead set the prototype to null without creating that property. A later assignment to a different object can still invoke an inherited setter. JSON does not allow computed property names. ECMAScript 2024 specifies this syntax; check compatibility if you target older runtimes.

Examples

{
  const key = "score";
  const token = Symbol("score");
  const obj = {
    [key]: 10,
    key: 20,
    [token]: 30,
    [1]: 40,
    "1": 50,
    ["__proto__"]: null,
  };

  console.log(obj[key]);
  console.log(obj.key);
  console.log(obj[token]);
  console.log(obj[1]);
  console.log(obj["__proto__"] === null && Object.getPrototypeOf(obj) === Object.prototype);
}

Result

10
20
30
50
true

`obj[key]` returns `10` from the property with key `"score"`, while `obj.key` returns `20` from the property with the literal key `"key"`. The symbol is a separate key. The later `"1"` definition replaces `[1]`, and the final check tests both the `__proto__` value and the unchanged prototype.

Related lessons

  • JavaScript · Lesson 17 · Advanced · Version: 4

Sources