paint-brush
Understanding Optional Chaining in JavaScript by@rahull
502 reads
502 reads

Understanding Optional Chaining in JavaScript

by RahulMarch 27th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

optional chaining is a modern language feature that allows you to safely navigate through and access deeply nested object properties. It does this by allowing you to chain together multiple levels of an object, and removes the need for the traditional 'if' statement. The syntax for Optional Chaining is simple: use a question mark (?) followed by a period.
featured image - Understanding Optional Chaining in JavaScript
Rahul HackerNoon profile picture


Are you writing code that needs to quickly access properties or invoke methods of an object—without worrying if the object or related data is null or undefined?


If so, then you need optional chaining in JavaScript!


Optional chaining is a modern language feature that allows you to safely navigate through and access deeply nested object properties.


It does this by allowing you to chain together multiple levels of an object, and replace the need for the traditional if statement.


This makes it easier to extract values from an object, no matter how deeply nested they may be.


For example, let's say you have an address object with a street property nested inside.


Using optional chaining, you could access the street with this short bit of code: address?.street.


This will attempt to look for the street property of your address object, and if it can’t find one (if the address itself is undefined), it simply returns undefined instead of throwing an error.


In a nutshell, this easy-to-use feature allows you to work with data more confidently and efficiently by providing a safe way to traverse and access deep nested objects without running into errors.

How to Use Optional Chaining in Javascript

When you work with objects and arrays in Javascript, you often need to access a certain property that may or may not exist.


For example, you may have an array where each element is an object containing some properties. But in each object, you don’t know if the property that you want to access will be there. In this case, Optional Chaining can be your savior!


Optional Chaining allows us to simplify our code by avoiding many of the checks that we need to do in order to make sure that an object has a certain property before accessing it.


The syntax for Optional Chaining is simple: use a question mark (?) followed by a period (.), both between the current value and the next part of your chain.


This might look something like this: object?.property?.nestedProperty.

For instance, say we had an array called states containing objects with properties such as name and capital.


We could use Optional Chaining to access the name of the capital city of Florida like so: states[2]?.capital?.name.


If either the element at index 2 or its capital property doesn’t exist, then nothing would be returned instead of an error being thrown—which makes Optional Chaining a great way of writing robust code without having to carry out all those checks manually!

When to Use Optional Chaining

You may be wondering when to use optional chaining in your code.

The answer is: anytime you need to access deep nested objects but aren’t sure if the property you want to access will be there.


By using Optional Chaining you can save yourself time and many lines of code. Instead of having to do checks manually, you can use this feature to make sure you safely navigate through properties without running into errors.


This is especially useful when you’re dealing with data that might not have the expected structure. Imagine you’re working with an API of some sort and the data you’re getting back from the API is not always consistent.


In these cases, you don’t know for sure if the property you’re trying to access will be there - so optional chaining can come in handy.


Another situation when you might use optional chaining is when you know your data will change, so it’s better to be safe and use this feature.


For example, if you’re developing a game, at some point in time you may need to access deeply nested objects, but you don’t know if the structure you’re expecting will be there.


By using optional chaining, you can avoid errors and ensure that your code will work under different conditions.


Regardless of the scenario, optional chaining is a powerful tool that can help you write code more efficiently and safely.

Potential Pitfalls of Using Optional Chaining

Using Optional Chaining in your code can make things easier to read and also provide some extra safety guards, but there are a few potential pitfalls you should be aware of when using it.

Obscuring Bugs

Optional Chaining can mask a bug in your code, since it will simply return undefined instead of throwing an error. As a result, a subtle bug could go unnoticed, which could be difficult to debug down the line.


If you’re not careful and diligent when writing code, Optional Chaining can hide a bug that may later cause issues in production.

Unintended Behavior With null and undefined

You should be aware of the difference between null and undefined.

Optional Chaining will return undefined if any part of the chain is undefined, but if one part of the chain is set to null, the rest of the chain won’t execute because it doesn't have a value to look for. For example:


var foo = { bar: undefined }
foo.bar?.baz // returns undefined
foo2 = { bar: null }
foo2.bar?.baz // returns undefined rather than throwing an error

You should also keep in mind that while Optional Chaining looks great with an arrow function, it only works within parenthesis:


var foo = { bar: () => 'baz' } // does **not** work as expected!

foo?.bar() // returns undefined // does **not


Examples of Optional Chaining in Javascript

Ready to dive into some examples to get a better idea of what's going on? Let's take a look at how optional chaining looks in JavaScript code.


Optional Chaining uses the syntax ?., meaning that your JavaScript code can look something like this:


user?.post?.comments?.author;


This will read each part of the expression before it gets an error, so if any part of the expression is undefined, it will simply return undefined without throwing an error – which is a big advantage!


In other words, instead of worrying about those pesky null values and writing lots of tedious if statements, you can use Optional Chaining and simplify your code significantly. It looks like this:


let author = user && user.post && user.post.comments && user.post.comments.author;

// same as with Optional Chaining:

let author = user?.post?.comments?.author;


See how much easier that is compared to writing out tons of if statements? This streamlines your code and reduces potential for errors in a big way!

Troubleshooting Optional Chains in JavaScript

Optional chaining in JavaScript can be a great way to simplify your code and make it easier to debug when things go wrong.


But sometimes, optional chaining can create more problems than it solves. Here are a few tips for troubleshooting optional chains in JavaScript.

Check the Syntax

The syntax of an optional chain statement is different from what you would usually write in JavaScript, so make sure that you’re not making any mistakes when writing the statement.


If you’re new to optional chaining, double check the syntax with other sources or tutorials to make sure that everything is correct.

Make Sure Your Data is Valid

When dealing with optional chains, keep in mind that if there’s a null value anywhere along the chain, then an error will be thrown.


Make sure that your data is valid before attempting to use an optional chain—if there’s something wrong with your data, then it won’t work as expected.

Use Optional Chaining Only When Necessary

When using optional chaining in JavaScript, always think carefully about where and when to use it—there’s no need to use an optional chain if it isn't really necessary.


Use it only when it makes sense and helps make your code clearer and simpler.

Finally, remember that if something isn’t working as expected with an optional chain statement, you can always reach out for help or advice from other developers who have experience using them in their projects.


With these tips and tricks, troubleshooting JavaScript Optional Chains should be a breeze!

Conclusion

In short, optional chaining is an incredibly useful feature of JavaScript that helps you simplify your code. It is a concise syntax for accessing nested object properties, protecting you from TypeError when those properties are null and undefined. With the optional chaining operator you can access properties from deep in nested objects without having to check the entire chain of objects.


It's a great tool if you need to access properties and don't want to bother with all the checks and conditionals.


Plus, it's very easy to remember and use, so it's definitely worth adding it to your arsenal of go-to coding tricks.


Also published here.