CKTIS / JavaScript
Computed property access
Bracket notation `obj[expr]` selects a property using the value of an expression. Use it to read or write properties or call methods whose keys are determined at runtime.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
object[expression]
object[expression] = value
object[expression](...args)
object?.[expression]Computed property access evaluates expr in obj[expr] to select a property key. obj.key always uses the string key "key", while obj[key] uses the value of the variable key. Brackets also allow keys containing spaces. In { [expr]: value }, the brackets mark a computed property name: they define a property in an object literal rather than read one from an existing object.
ToPropertyKey converts the key value to a primitive, preserves it if it is a Symbol, and otherwise converts it to a string. So obj[1] and obj["1"] address the same property. Converting an object used as a key can run code and throw an exception.
An ordinary read can follow the prototype chain and invoke a getter. A missing property gives undefined, but an existing property can also produce undefined. Use Object.hasOwn(obj, key) to test for an own property. obj[key] = value follows normal assignment rules, and a direct obj[key]() call uses obj as the receiver, just like obj.method().
Reading directly from null or undefined throws TypeError. With such a base, obj?.[expr] returns undefined without evaluating expr; this form cannot be an assignment target. Bracket access is ECMAScript syntax, not a browser API. Check that your target runtime supports ?. and Object.hasOwn.
Brackets do not validate external keys. Before reading or writing based on untrusted input, restrict keys to an explicit allowlist. Object.hasOwn alone is not an authorization check.
Examples
{
const key = "total points";
const token = Symbol("bonus");
const scores = { [key]: 7, [token]: 2, "1": "first" };
console.log(`before: ${scores[key]}`);
scores[key] = 9;
console.log(`after: ${scores[key]}`);
console.log(`literal key: ${scores.key}`);
console.log(`symbol key: ${scores[token]}`);
console.log(`numeric key: ${scores[1]}`);
let evaluations = 0;
const missing = null;
console.log(`optional: ${missing?.[evaluations++]}`);
console.log(`evaluations: ${evaluations}`);
}Result
before: 7 after: 9 literal key: undefined symbol key: 2 numeric key: first optional: undefined evaluations: 0
The example updates a key containing a space and shows that `scores.key` looks for the literal key `"key"`. The final access skips `evaluations++`, so the counter stays at `0`.
Related lessons
- JavaScript · Lesson 24 · Advanced · Version: 4
- JavaScript · Lesson 25 · Advanced · Version: 4
- JavaScript · Lesson 29 · Advanced · Version: 4