CKTIS / JavaScript
Computed method keys in object literals
Use `[expr](...) { ... }` in an object literal to define a method under a key determined by an expression. The key is a string or a symbol.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const obj = { [expression](parameter) { /* method body */ } };
obj[key](argument);Object computed method keys let you choose a method’s property key with an expression in an object literal: [expr](...) { ... }. Without square brackets, key() { ... } always uses the literal key "key", regardless of any variable named key.
The expression runs each time the literal is evaluated, not each time the method is called. To get the key, JavaScript converts the result to a primitive if necessary, keeps a symbol unchanged, and converts any other primitive to a string. For example, 1 becomes "1". If evaluation or conversion throws, object creation stops. Changing a variable used to compute the key later does not rename the existing property.
In obj[key](...), the brackets look up the property. Calling it in this form sets this inside the method to obj. If the lookup yields a non-callable value, as it does for a missing property, the call throws TypeError.
An ordinary method defined this way is an own, enumerable property of the object. If two ordinary method definitions in the same literal produce the same key, the later one replaces the earlier one. Different parameter lists do not create overloads.
Examples
const key = "say" + "Hi";
const loud = Symbol("loud");
const obj = {
label: "Ada",
[key]() {
return "Hi, " + this.label;
},
[loud]() {
return this.label.toUpperCase();
},
};
console.log(obj[key]());
console.log(obj[loud]());Result
Hi, Ada ADA
`[key]` defines a method under the string key `"sayHi"`, while `[loud]` uses a `Symbol` value. Both calls read `label` from `obj` through `this`.
Related lessons
- JavaScript · Lesson 8 · Advanced · Version: 4