You can use optional chaining (?.
) to access object properties or methods (that could potentially be a nullish value) in the following ways:
Using the Dot Notation
The dot notation has the following syntax for accessing object property or method:
// ES11+ obj?.prop obj.method?.(args)
It returns undefined
if the left operand evaluates to a nullish value.
You can use the dot notation as long as the property name does not have a space or a hyphen, starts with a number or is dynamically determined. For example:
// ES11+ // ... const authorName = post?.author?.name; const result = post.callback?.(); // ...
Using the Bracket Notation
The bracket notation has the following syntax for accessing object property or method:
// ES11+ obj?.['prop'] obj.['prop'].method?.(args)
It returns undefined
if the left operand evaluates to a nullish value.
When/if a property name has a space or a hyphen, starts with a number or is dynamically determined, it can only be accessed using the bracket notation. For example:
// ES11+ const post = posts?.[0]; const authorName = post?.['author-name']; // ...
You can also use it in place of the dot notation. However, the dot notation has a simpler syntax and should generally be preferred wherever possible.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.