Sub topic 2
Dynamic Keys, Optional Calls and Nested Defaults
This chapter assumes you already know dot and bracket property access, how to call functions and methods, and how plain ?. and ?? behave on their own.
Dynamic Keys and Array Indexes with ?.[]
Bracket access with a computed key needs its own optional form, ?.[]. Writing obj?.[key] returns undefined when obj is null or undefined. If obj exists, it reads the property as normal.
const translations = { en: { greeting: "Hello" } };
const lang = "fr";
console.log(translations[lang]?.greeting); // undefined
const items = null;
console.log(items?.[0]); // undefinedA common mistake is writing items?[0]. That is not optional chaining. JavaScript tries to read it as the start of a ternary expression and throws a syntax error. The dot is required: ?.[.
Calling Methods That Might Not Exist with ?.()
The form fn?.() calls fn only if it is not nullish. This is useful for optional callbacks and for methods that only some objects have.
const logger = { info: (msg) => console.log(msg) };
logger.info?.("started"); // logs "started"
logger.debug?.("details"); // does nothing, returns undefined
const onDone = undefined;
onDone?.(); // does nothingAlso note what the ?. guards. In logger.debug?.(), it guards the method, not logger. If logger itself might be missing, write logger?.debug?.().
Reading Nested Data with ?. and ??
An optional chain gives back undefined when any link in it is missing. Put ?? at the end to swap that undefined for a real default.
const response = { data: { user: { name: "Ada" } } };
const empty = {};
const name1 = response.data?.user?.name ?? "Anonymous";
const name2 = empty.data?.user?.name ?? "Anonymous";
console.log(name1); // "Ada"
console.log(name2); // "Anonymous"Use ?? here, not ||. With ||, a real name of "" would be replaced by the default.
Exercise
Given const cfg = { handlers: null }, what does cfg.handlers?.["save"]?.() ?? "none" evaluate to, and does it throw?
Show answer
It evaluates to "none" and does not throw. cfg.handlers is null, so ?.["save"] short-circuits the rest of the chain to undefined, and ?? replaces undefined with "none".
Exercise
Why does const x = { run: 5 }; x.run?.(); throw?
Show answer
x.run is 5, which is not nullish, so the call goes ahead. Calling a number throws a TypeError because 5 is not a function.