The safe navigation operator is simply another name for the optional chaining operator (?.), which was introduced in ES11. It evaluates an expression from left-to-right; when/if the left operand evaluates to a nullish value, it stops the execution of the entire chain and short-circuit evaluates the expression to undefined. This helps avoid having the need to add sequential explicit null-safe checks.
It has the following syntax:
obj.value?.prop
obj.value?.[expr]
obj.array?.[index]
obj.function?.(args)
In JavaScript, you can use optional chaining with:
- Object properties and methods;
- Expressions;
- Arrays;
- Function calls.