CKTIS / JavaScript
Array and computed property indexing
The same square brackets select array elements and access object properties by keys computed at runtime.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
obj[keyExpr]
obj.name
obj[keyExpr] = value
({ [keyExpr]: value })
arr[index]
arr.at(index)
Object.hasOwn(arr, index)Array and computed property indexing share bracket notation. obj[keyExpr] evaluates the expression inside the brackets and applies ToPropertyKey, producing a string or a Symbol key. Use it to read or assign a value. By contrast, obj.key always names the literal key "key"; it does not read a variable called key. In { [key]: value }, the brackets compute the name of a property being defined, rather than accessing an existing property.
On an array, arr[0] and arr["0"] select the same first element. Array index keys are canonical decimal strings for integers from 0 through 2 ** 32 - 2. Creating an own element at or beyond the current length extends length to the index plus one and can leave holes. The key "01" is not an array index; adding that property does not change length.
Reading a missing index is not a bounds error: the lookup can find an inherited property, or return undefined if no property exists anywhere on the prototype chain. A hole has no own property at that index. Object.hasOwn(arr, index) distinguishes a hole from an own element whose value is undefined. Bracket access on null or undefined throws a TypeError.
arr[-1] looks up the property "-1"; arr.at(-1) reads the last position of a nonempty array. at() returns undefined if the resolved position is out of range. Check target runtime support for at() and Object.hasOwn(). Validate keys from untrusted input against an allowlist before using them for property access.
Examples
{
const arr = ["A"];
arr[2] = undefined;
arr[3] = "D";
arr["01"] = "tag";
const key = "score";
const obj = { [key]: 7 };
console.log(`${arr[0]} ${arr["0"]}`);
console.log(`${arr.length} ${arr["01"]}`);
console.log(`${arr[1]} ${arr[2]}`);
console.log(`${Object.hasOwn(arr, 1)} ${Object.hasOwn(arr, 2)}`);
console.log(`${arr[-1]} ${arr.at(-1)}`);
console.log(`${obj[key]} ${obj.key}`);
}Result
A A 4 tag undefined undefined false true undefined D 7 undefined
Indices `1` and `2` both read as `undefined`, but only index `2` has an own element. The key `"01"` does not affect the length of `4`. The object literal defines `score`, not `key`.
Related lessons
- JavaScript · Lesson 27 · Advanced · Version: 4