Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Object computed property access

Use `obj[expr]` to read or assign a property selected by an expression instead of using a fixed name after a dot.

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

Syntax

obj[expr]             // read using a computed key
obj[expr] = value     // assign using a computed key
obj?.[expr]           // optional computed access
obj.name              // access the fixed string key "name"
({ [expr]: value })   // define a property in an object literal

Object computed property access uses obj[expr]: JavaScript evaluates expr to select a property to read or assign. obj.key always means the string key "key"; obj[key] uses the value of the variable key. By contrast, { [expr]: value } defines a property while creating an object rather than reading one from an existing object.

ToPropertyKey first converts the key value to a primitive. It preserves a Symbol result and converts any other result to a string. Thus obj[1] and obj["1"] refer to the same property. Brackets support strings with spaces, but obj["#secret"] does not access the private class field #secret.

On an ordinary object, a read can find an inherited property or invoke a getter. A property missing throughout the prototype chain reads as undefined, just like a property whose value is undefined. Use Object.hasOwn(obj, key) to check whether the property belongs directly to the object. Validate untrusted keys against an allowlist before reading or writing; Object.hasOwn alone does not replace that check.

A normal read from null or undefined throws TypeError if no earlier error occurs. obj?.[expr] returns undefined for either of those base values without evaluating expr. It does not catch getter errors and cannot be used as an assignment target. This is JavaScript syntax, not a DOM API; check support for ?. and Object.hasOwn when targeting older runtimes.

Examples

{
  const key = "display count";
  const tag = Symbol("status");
  const obj = { key: 0, [key]: 2, [tag]: "ready" };

  obj[key] = obj[key] + 1;
  console.log(obj[key]);
  console.log(obj.key);
  console.log(obj[tag]);

  const absent = null;
  console.log(String(absent?.[key]));
}

Result

3
0
ready
undefined

`obj[key]` changes from `2` to `3`, but `obj.key` is still `0`. `obj[tag]` reads `ready` using a `Symbol` key, and optional access on `null` yields `undefined`.

Related lessons

  • JavaScript · Lesson 38 · Advanced · Version: 4
  • JavaScript · Lesson 44 · Advanced · Version: 4

Sources