How can I safely read a nested property that may be missing?
Quick answer
Use ?. at each point where the value to its left might be null or undefined. For example, user?.profile?.name evaluates to undefined if user or profile is nullish, rather than trying to read the remaining property. Ordinary chained access can fail at a nullish link. Optional chaining gives you a result; it does not decide what your application should do when the value is missing. [S1]
The question, the details, the next step.
A practical checklist
Mark which objects or nested links may be
nullorundefined.Add
?.at each possibly nullish link before reading farther.Account for the
undefinedresult when a nullish value interrupts the chain.Choose an explicit response that fits the application.
Check the expression with a complete object and one with a missing intermediate link.
A few more useful answers
Does optional chaining replace a missing value with a default?
No. If a nullish value interrupts the chain, the expression evaluates to undefined. Decide separately whether to use a fallback or handle the missing value another way. [S1]
Should I use `?.` on every property access?
Use it where a value to the left may be null or undefined and you want to avoid attempting the remaining access. It does not validate required data or decide what missing information should mean. [S1]
Sources
References used for this guide.
- [S1] Optional chaining (?.) — JavaScript | MDN developer.mozilla.org · Checked
