Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Computed property and method keys

Square brackets in a property or method definition let an expression determine its key. The key is established when the object is created; changing the variable used in that expression later does not rename the property.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

({ [keyExpression]: value, [methodKeyExpression](parameters) { /* body */ } })

In an object literal, [expression]: value evaluates the expression and uses its result as the property key. The form [expression](parameters) {} defines a method with a computed name, without a colon or the function keyword. This method-name syntax also works in classes.

To obtain a property key, JavaScript first converts an object to a primitive value. If the resulting or already primitive value is a symbol, JavaScript uses it unchanged as the key; otherwise, it converts the value to a string. For example, [1] and ["1"] identify the same key, while a standard symbol wrapper yields the underlying symbol, not a string. In an object literal, the key expression is evaluated when the object is created, not on every read.

Distinguish the definition { [key]: value } from the access obj[key]. The form { key: value } uses the literal name key, and obj.key reads that name, not the variable's value. Brackets are also needed when calling a method whose name is stored in a variable: obj[methodKey]().

The syntax dates from ECMAScript 2015 and is widely supported in modern browsers; it requires no Web API. JSON allows neither computed keys nor methods. One special case: ["__proto__"]: value creates an ordinary own property, whereas __proto__: value in an object literal is prototype-setting syntax.

Reference identifiers covered by this entry: Computed property and method keys.

Examples

let key = "score";
const methodKey = "read";
const record = {
  [key]: 7,
  [methodKey]() {
    return this.score;
  },
};
key = "other";
console.log(record.score);
console.log(record[methodKey]());
console.log(record[key]);

Result

7
7
undefined

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources