DEV Community

Cover image for JavaScript's Optional Chaining (?.) Operator
Code of Relevancy
Code of Relevancy

Posted on • Updated on

JavaScript's Optional Chaining (?.) Operator

JavaScript is one of the most popular and widely used programming languages for web development. With its vast array of features and capabilities, JavaScript developers are continuously pushing the limits of what's possible on the web.

In this article, we'll be exploring an exciting feature in JavaScript known as the Optional Chaining Operator (?.). This operator has been introduced in ECMAScript 2020 and has since become a staple in modern JavaScript development. The Optional Chaining Operator allows developers to access properties of an object without worrying about TypeError, making the code more concise and less prone to bugs. We'll learn how you can leverage its power to simplify your code and improve the overall readability of your applications. So buckle up and get ready to unleash the power of JavaScript's Optional Chaining (?.) Operator!


Optional chaining (?.)

The Optional Chaining ?. operator is a powerful tool for accessing object properties or calling functions in JavaScript. Unlike traditional methods, which can result in a TypeError when the object is undefined or null, the Optional Chaining operator short circuits and simply returns undefined. This makes the code more concise and reduces the risk of encountering bugs, making it an essential tool for modern JavaScript development.

Image description


Syntax

The syntax is straightforward and easy to understand. The operator is placed after the object you wish to access and before the property, array expression, or function call you want to make.

Here's how it works:

obj.val?.prop - Accesses the prop property of the obj.val object, only if obj.val exists and is not null or undefined.

obj.val?.[expr] - Accesses a property or an array element of obj.val using an expression expr, only if obj.val exists and is not null or undefined.

obj.func?.(args) - Calls the function obj.func with the given arguments args, only if obj.func exists and is not null or undefined.


Optional chaining ?. is used to access object properties and methods in a safe way, by handling the possibility of encountering null or undefined values. In React.js or Next.js, it can be used to access properties in state or props objects and to call methods on components, without risking runtime errors from trying to access a property or method on a null or undefined value.

Let's say, instead of writing:

let name = user && user.name;
Enter fullscreen mode Exit fullscreen mode

you can write:

let name = user?.name;
Enter fullscreen mode Exit fullscreen mode

This can simplify your code and make it more concise. Useful in cases where you are not sure if the object exists or not.


It's important to note that the Optional Chaining operator cannot be used on a non-declared root object. Attempting to do so will result in a ReferenceError being thrown, indicating that the root object is not defined. However, the operator can be used on a root object that has a value of undefined.

Image description


The "non-existing property" problem

If you've just started to read the tutorial and learn JavaScript, maybe the problem hasn't touched you yet, but it's quite common.

As an example, let's say we have user objects that hold the information about our users.

Most of our users have addresses in user.address property, with the street user.address.street, but some did not provide them.

In such case, when we attempt to get user.address.street, and the user happens to be without an address, we get an runtime error:

Image description


Function Calls with Optional Chaining

The Optional Chaining operator is not just useful for accessing object properties, but it can also be applied to function calls. This makes it an ideal tool for handling scenarios in which the method you are trying to call may not exist. This is especially useful when working with APIs that have varying levels of support, or when dealing with features that may not be available on the user's device.

Image description

In this case, if the customMethod is not found on the someInterface object, the expression will return undefined instead of throwing an error. This allows your code to gracefully handle such scenarios and avoid the risk of unintended exceptions. With the Optional Chaining operator, you can write cleaner and more robust code that is better equipped to handle the complexities of real-world development.


Optional chaining with expressions

The Optional Chaining operator can also be combined with bracket notation to access properties with dynamic names. This is done by passing an expression as the property name, inside square brackets [].

Image description


Optional chaining not valid on the left-hand side of an assignment

It is not possible to use the Optional Chaining operator for assigning values to object properties. Attempting to do so will result in a SyntaxError.

Image description


What are the downsides of optional chaining?

Optional chaining is easy to misuse and can potentially confuse future readers of your code in certain scenarios. This operator makes it easier for devs to express chained nullable references in a much concise manner.


Don't overuse the optional chaining

We should use ?. only where it's ok that something doesn't exist.

Let's say, if according to our code logic user object must exist, but address is optional, then we should write user.address?.street, but not user?.address?.street.

Then, if user happens to be undefined, we'll see a programming error about it and fix it. Otherwise, if we overuse ?., coding errors can be silenced where not appropriate, and become more difficult to debug.


🍀Conclusion

The Optional Chaining (?.) operator is a powerful and elegant feature in JavaScript that can simplify our code and prevent runtime errors. By allowing us to safely access properties and call methods without having to check for undefined values, it allows us to write more concise and readable code. It's important to understand when and how to use this operator effectively, as overusing it can hide potential errors and make debugging more difficult. When used strategically, the Optional Chaining operator can be a valuable tool in our JavaScript toolkit.


🍀Support

Please consider following and supporting us by subscribing to our channel. Your support is greatly appreciated and will help us continue creating content for you to enjoy. Thank you in advance for your support!

YouTube
Discord
GitHub

Top comments (2)

Collapse
 
9opsec profile image
9opsec

I've been seeing this syntax and wondering about its purpose. Thanks for posting!

Collapse
 
codeofrelevancy profile image
Code of Relevancy

You're welcome sir, I'm glad I could help clarify the purpose of the optional chaining.. if you have any further questions or need more information, please feel free to ask..