CKTIS / JavaScript
Property access syntax
Use dot notation for a fixed name and brackets for a computed key. Learn how private access differs and exactly when optional chaining skips a read.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
obj.name
obj[expr]
obj.#name
obj?.name
obj?.[expr]
obj?.#nameProperty access syntax selects a member of a value. In obj.name, name is a fixed string key, not a variable. After the dot comes an IdentifierName, so obj.default is valid, but the key "display-name" needs obj["display-name"]. In obj[expr], JavaScript evaluates the expression and converts its result to a key: it obtains a primitive, keeps it if it is a Symbol, and otherwise converts it to a string. That is why obj[1] and obj["1"] use the same key.
On an ordinary object, a read can find an own or inherited property and can invoke a getter. A missing property yields undefined, but an existing property can also have that value. Use Object.hasOwn(obj, key) to test for an own property. Both obj.name and obj["name"] can be assignment targets, but the property's rules govern the write, which may invoke a setter. Both obj.show() and obj["show"]() pass obj as this; just retrieving the function does not bind it.
obj.#name refers to a private element, not a property with the string key "#name". The private name must be declared in a class scope that is lexically in reach, or the code is a SyntaxError. Reading from an object without that private element throws a TypeError. obj["#name"] cannot access it.
An ordinary read from null or undefined throws a TypeError. With obj?.name or obj?.[expr], either of those base values makes the uninterrupted chain short-circuit to undefined, without evaluating expr. obj?.#name still follows the private-access rules. ?. does not catch exceptions from getters, and an optional chain cannot be an assignment target.
Validate untrusted keys against an allowlist, especially before writing: an unchecked key can select an unintended property, and some writes can alter a prototype. These forms are part of ECMAScript 2024, not browser APIs; check support in your target runtime.
Examples
(() => {
const key = "display-name";
const token = Symbol("token");
const obj = {
name: "Ada",
[key]: "A. Lovelace",
1: "one",
[token]: "symbol",
show() { return this.name; },
};
console.log(obj.name);
console.log(obj[key]);
console.log(obj[1] === obj["1"]);
console.log(obj[token]);
console.log(obj["show"]());
console.log(obj.profile?.[key]);
})();Result
Ada A. Lovelace true symbol Ada undefined
The `true` comparison shows that `1` and `"1"` select the same key. The bracket-form call keeps `obj` as `this`, and the last read short-circuits because `profile` is missing.
Related lessons
- JavaScript · Lesson 20 · Advanced · Version: 4