Sub topic 5
Dynamic Keys and Array Indexes with ?.[]
This chapter assumes you already know how dot and bracket property access work, how arrays are indexed, and how the ?. operator from the previous chapter protects a dot access. Here we cover the bracket form, ?.[]. You use it when the property name is computed at runtime, comes from a variable, is a symbol, or is an array index.
Why Dot Access Is Not Enough
Dot access needs a property name you can write in the source code as an identifier. Many real lookups don't fit that rule:
- A key stored in a variable, such as a language code or a user ID.
- A key that isn't a valid identifier, such as
"content-type"or"2024". - An array index.
- A
Symbolkey.
Bracket notation handles all of these. The optional form, ?.[], adds the same protection that ?. gives dot access. If the value to the left is null or undefined, the expression returns undefined and does not throw.
const translations = { en: { greeting: "Hello" } };
const lang = "fr";
console.log(translations[lang]?.greeting); // undefined
const items = null;
console.log(items?.[0]); // undefinedThe first line uses ordinary brackets to look up "fr", which is missing, and then uses ?. to protect the .greeting read. The second line guards the array itself: items is null, so items?.[0] returns undefined and skips the lookup that would have thrown.
The Syntax and Why It Has a Dot
People often expect the syntax to be obj?[key]. JavaScript can't use that form because ? already starts the conditional (ternary) operator. Consider a?[1]:[2]. That is a valid ternary that picks between two arrays. If ?[ also meant optional access, the parser could not tell which one you meant. So the dot is required in every optional form:
| Form | Meaning |
|---|---|
| `obj?.prop` | Optional dot access |
| `obj?.[expr]` | Optional bracket access |
| `fn?.(args)` | Optional call |
The same ambiguity leads to a small lexer rule. A ?. followed directly by a decimal digit is not read as optional chaining. Instead, the parser reads ? as the ternary operator and .5 as a number:
const flag = true;
console.log(flag?.5:1); // 0.5 (parsed as flag ? .5 : 1)You will rarely write this on purpose. It does explain why arr?.0 is not a way to read index 0. That code is a syntax error, or it turns into a ternary if a : follows it. Indexes always go in brackets: arr?.[0].
How ?.[] Is Evaluated
The operator guards the value to its left. It does not guard the key, and it does not guard the result.
Three facts follow from this order.
- The key expression runs only if the base is not nullish. When the base is
null, a function call or increment inside the brackets never runs. The chapter on short-circuiting covers this in detail. - A nullish key is still a key.
obj?.[null]looks up the property named"null", because keys are converted to strings. The?.checksobj, not the key. - A missing property gives
undefinedthe normal way. Ordinary bracket access already returnsundefinedfor a missing key or an out-of-range index.?.adds nothing there.
const lookup = { null: "a key literally named null", undefined: "and this one" };
let key = null;
console.log(lookup?.[key]); // "a key literally named null"
console.log(lookup?.[undefined]); // "and this one"
const empty = null;
console.log(empty?.[key]); // undefined, because empty is nullishArrays: What ?.[] Protects and What It Doesn't
A common mistake is to think arr?.[5] protects you from an index that is out of range. Plain arr[5] never throws for a missing index. It returns undefined. The question mark only matters when arr itself could be null or undefined.
const scores = [10, 20, 30];
console.log(scores[5]); // undefined, no error
console.log(scores?.[5]); // undefined, the ?. was unnecessary
let maybeScores; // undefined
console.log(maybeScores?.[0]); // undefined
// console.log(maybeScores[0]); // TypeError: Cannot read properties of undefinedThe danger usually comes one step later. You read an element and then access something on it:
const users = [{ name: "Ada" }];
console.log(users[0]?.name); // "Ada"
console.log(users[3]?.name); // undefined
// console.log(users[3].name); // TypeError: users[3] is undefinedWhere you put the ?. depends on which value might be missing:
| Expression | Guards against |
|---|---|
| `users?.[0].name` | `users` being nullish (throws if index 0 is missing) |
| `users[0]?.name` | element 0 being missing (throws if `users` is nullish) |
| `users?.[0]?.name` | both |
Put ?. right after each value that is allowed to be absent. Leave it out where absence would be a bug. The tutorial's chapter on overuse covers that judgment.
Two-dimensional data
Grids and matrices show why you may need one ?. per level:
const grid = [
[1, 2, 3],
[4, 5, 6],
];
function cell(g, row, col) {
return g?.[row]?.[col];
}
console.log(cell(grid, 1, 2)); // 6
console.log(cell(grid, 9, 0)); // undefined, row 9 does not exist
console.log(cell(null, 0, 0)); // undefined, no grid at allIf you drop the second ?., cell(grid, 9, 0) throws. grid[9] is undefined, and reading [0] from undefined is a TypeError.
Negative indexes and at()
Brackets do not count from the end. arr[-1] looks up a property named "-1", which normally doesn't exist. To read from the end, combine an optional call with Array.prototype.at:
const queue = ["a", "b", "c"];
const none = undefined;
console.log(queue?.[-1]); // undefined, no property "-1"
console.log(queue?.at(-1)); // "c"
console.log(none?.at(-1)); // undefinedStrings, Symbols and Other Keys
?.[] works on any value that supports bracket access, including strings and symbol keys:
const initial = (name) => name?.[0];
console.log(initial("Grace")); // "G"
console.log(initial(null)); // undefined
const meta = Symbol("meta");
const record = { [meta]: { version: 2 } };
const missing = null;
console.log(record?.[meta]?.version); // 2
console.log(missing?.[meta]?.version); // undefined
const headers = { "content-type": "text/html" };
console.log(headers?.["content-type"]); // "text/html"Primitives other than null and undefined count as non-nullish. (42)?.["toFixed"] returns the toFixed function from Number.prototype. It does not stop the chain.
Gotchas
Maps are not bracket-accessible
A Map stores its entries internally, not as properties. Bracket access on a Map, optional or not, reads ordinary object properties and misses the entries:
const cache = new Map([["user:1", { name: "Ada" }]]);
console.log(cache?.["user:1"]); // undefined, wrong API
console.log(cache?.get("user:1")?.name); // "Ada"
const noCache = null;
console.log(noCache?.get("user:1")?.name); // undefinedInherited keys are found too
With dynamic keys, you may look up a key that exists on the prototype chain without meaning to. ?.[] doesn't change this:
const counts = { apples: 3 };
const fruit = "constructor";
console.log(counts?.[fruit]); // [Function: Object]
const safe = counts && Object.hasOwn(counts, fruit) ? counts[fruit] : undefined;
console.log(safe); // undefinedIf keys come from user input, use Object.hasOwn, an object created with Object.create(null), or a Map.
Assignment is not allowed, but delete is
You can't write to an optional chain. obj?.[key] = value is a SyntaxError. The chapter on syntax limitations covers the full list. delete is allowed. If the base is nullish, delete does nothing and returns true:
const session = { token: "abc" };
const noSession = null;
const field = "token";
console.log(delete session?.[field]); // true, property removed
console.log(session); // {}
console.log(delete noSession?.[field]); // true, nothing to deleteCommon Errors at a Glance
| Mistake | What happens | Fix |
|---|---|---|
| `obj?[key]` | Parsed as a ternary, usually a SyntaxError | `obj?.[key]` |
| `arr?.0` | SyntaxError or an accidental ternary | `arr?.[0]` |
| `arr?.[i].name` when the element may be missing | TypeError on the missing element | `arr?.[i]?.name` |
| `map?.[key]` | Always `undefined` for entries | `map?.get(key)` |
| `arr?.[-1]` to get the last item | `undefined` | `arr?.at(-1)` |
| `obj?.[key] = v` | SyntaxError | Guard with `if (obj)` and then assign |
Exercise
Given const data = { rows: [[1, 2], [3, 4]] }; and const empty = {};, write one expression that reads row r and column c from .rows without throwing, whether the object lacks rows, the row is missing, or the object is empty. What do data with r=1, c=0 and empty with r=0, c=0 return?
Show answer
obj.rows?.[r]?.[c] (or obj?.rows?.[r]?.[c] if obj itself might be nullish). With data and r=1, c=0 it returns 3. With empty it returns undefined: empty.rows is undefined, so ?.[r] stops the chain there.
Exercise
What does each line print, and why? const list = [5, 6]; console.log(list?.[2]); let n = null; console.log(n?.[0]); console.log(true?.5:9);
Show answer
undefined, because index 2 is out of range and normal bracket access returns undefined (the ?. played no part). Then undefined, because n is null and the chain stops. Then 0.5, because ?. followed by a digit is not optional chaining, so the line is parsed as the ternary true ? .5 : 9.
Exercise
A function receives settings, which may be undefined, and a user-supplied key. A teammate writes return settings?.[key];. Name two ways this can return a value the teammate didn't intend, and give a safer version.
Show answer
First, inherited properties: a key such as "constructor" or "toString" returns a function from Object.prototype. Second, if settings is a Map, bracket access ignores its entries, so the function returns undefined even when the key exists. A safer version for plain objects is return settings != null && Object.hasOwn(settings, key) ? settings[key] : undefined;. For a Map, use settings?.get(key).