CKTIS / JavaScript
Object shorthand and computed property access
Use property shorthand when a variable and its property share a name. Use brackets to compute a key when defining, reading, or writing a property.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const obj = { name, [keyExpression]: value };
obj.name;
obj[keyExpression];
obj[keyExpression] = newValue;Object shorthand and computed property access solve different problems. In an object literal, { name } creates an own data property with the key "name" and the current value of the variable name. For an ordinary name, this is shorthand for { name: name }. Reassigning the variable later does not update the property. Reading an undeclared identifier throws a ReferenceError.
In { [key]: value }, the bracketed expression is evaluated during object creation to determine the key of an own data property. Property keys are strings or symbols: a symbol keeps its identity, while the number 1 becomes the key "1". By contrast, { key: value } uses the literal key "key".
When accessing a property, obj[key] evaluates the key expression, while obj.key always means obj["key"]. Both forms support reads and assignments. Brackets also let you use keys like "bonus-points" and symbols. An ordinary read checks the object and its prototype chain: if the property is absent throughout, the result is undefined. Access on null or undefined throws a TypeError.
Watch for __proto__: in a literal, { __proto__: value } sets the prototype if value is an object or null and does not create an own data property. { ["__proto__"]: value } creates an own data property instead. Do not write properties using untrusted keys without checking them against an allowlist. This is ECMAScript syntax, not a browser API; check support in your target runtime.
Examples
{
let score = 7;
const key = "bonus-points";
const token = Symbol("bonus-points");
const obj = { score, [key]: 14, [token]: 21 };
score = 8;
console.log(`${obj.score} | ${obj[key]} | ${obj.key} | ${obj[token]}`);
obj[key] = 15;
console.log(String(obj["bonus-points"]));
}Result
7 | 14 | undefined | 21 15
`obj.score` remains `7` after `score` is reassigned to `8`. `obj[key]` reads `14`, `obj.key` yields `undefined`, and `obj[token]` reads the separate symbol-keyed property. Assigning through `obj[key]` then makes `obj["bonus-points"]` return `15`.
Related lessons
- JavaScript · Lesson 22 · Advanced · Version: 4