What does the optional chaining operator actually do?
The optional chaining operator stops the whole chain when it meets a value that is missing. Instead of throwing an error, the expression simply gives back the empty value, and the rest of the chain is never run.
const response = { data: { user: { name: 'Ada' } } };
console.log(response?.data?.user?.name); // Ada
console.log(response?.missing?.user?.name); // undefined, and no crash
const empty = {};
try {
console.log(empty.data.user.name);
} catch (error) {
console.log('crashed:', error.name); // TypeError
}
console.log(empty?.data?.user?.name); // undefined
The important detail is that the short-circuit happens at the first missing step, and everything after that step is skipped. If you write response?.data.user.name and the data property is missing, the chain stops at the question mark and the later property accesses never happen. That is why no error appears. The question mark protects the whole expression to its right, and not only the one property that sits next to it.
Two more points are worth knowing. Optional chaining does not tell the difference between null and a missing property, because both of them stop the chain. You can also use it on a function call, so obj.method?.() calls the method only when the method is really there.
There is one thing that you are not allowed to do. You cannot write an optional chain by itself as a statement. The language needs a chain to end in a property, a call, or an assignment, so you cannot write obj?.prop on a line by itself. That rule exists so that the operator cannot be used to quietly swallow a real mistake in your code.