Sub topic 5
Dynamic Keys and Array Indexes with ?.[]
This chapter assumes you know bracket property access (obj[key]), arrays and their indexes, and the basic ?. operator from the previous chapter. The dot form obj?.name only works when you can type the property name in your code. When the key is stored in a variable, computed at runtime, or is an array index, you need the bracket form: ?.[].
The Syntax
The bracket form puts the dot before the opening bracket:
const translations = { en: { greeting: "Hello" } };
const lang = "fr";
console.log(translations[lang]?.greeting); // undefined
console.log(translations?.[lang]); // undefined
const items = null;
console.log(items?.[0]); // undefinedThe rule matches ?.. If the value to the left of ?.[ is null or undefined, the expression evaluates to undefined and no lookup happens. If not, it behaves exactly like value[key].
Why the Dot Is Required
You might expect items?[0], but that form already means something else in JavaScript. A ? followed by an expression starts a conditional (ternary) expression: items ? [0] : other. To avoid that ambiguity, the language requires ?. before the bracket. Leaving out the dot is a common mistake, and it usually shows up as a confusing SyntaxError about a missing :.
Computed Keys
?.[] is useful with lookup tables keyed by user input or configuration:
const handlers = {
click: { label: "Clicked" },
hover: { label: "Hovered" },
};
function describe(eventType) {
return handlers[eventType]?.["label"];
}
console.log(describe("click")); // "Clicked"
console.log(describe("scroll")); // undefinedHere handlers[eventType] may be undefined for unknown events, and ?.["label"] stops the chain before it throws. The brackets can hold any expression, including template literals: config?.[${env}Url].
Array Indexes
The same form protects array access when the array itself might be missing:
const response = { results: null };
console.log(response.results?.[0]); // undefined
// console.log(response.results[0]); // TypeError: Cannot read properties of null
const matrix = [[1, 2], [3, 4]];
console.log(matrix?.[1]?.[0]); // 3
console.log(matrix?.[5]?.[0]); // undefinedIn matrix?.[5]?.[0], the first ?.[ is not what saves you. matrix exists, so matrix[5] runs and returns undefined. The second ?.[ is the one that prevents undefined[0] from throwing.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| `items?[0]` | Parsed as a ternary, so you get a SyntaxError | Write `items?.[0]` |
| Expecting `arr?.[10]` to guard against an out-of-range index | Not needed: an out-of-range index already returns `undefined` | Guard the next step instead: `arr[10]?.name` |
| Using `?.[]` on a `Map` | `map?.["key"]` reads an object property, not a Map entry | Use `map?.get("key")` |
| Expecting a negative index to count from the end | `arr?.[-1]` looks up the property `"-1"`, which is `undefined` | Use `arr?.at(-1)` |
Strings work too, because they support index access: "abc"?.[1] is "b", and null?.[1] is undefined.
Exercise
Given const data = { rows: [{ id: 7 }] };, what do data.rows?.[0].id, data.rows?.[3]?.id, and data.cols?.[0] return, and which of them would throw if you removed every ?.?
Show answer
They return 7, undefined, and undefined. Without ?., data.rows[0].id still returns 7. data.rows[3].id throws, because data.rows[3] is undefined. data.cols[0] throws, because data.cols is undefined.
Exercise
A colleague writes const first = list?[0]; and gets a SyntaxError. Why, and what is the correct expression?
Show answer
list?[0] starts a ternary, list ? [0] : ..., which is missing its : branch. The optional bracket form needs the dot: list?.[0].