Let's deep dive into the concept of Optional Chaining in JavaScipt.
With optional chaining, we can check to see if something exists and handle an error gracefully.
A Thread 👇
What the heck is Optional chaining? 🥴
The optional chaining " ?." is a recent addition to the language which is a secure way to access nested object properties, even if an intermediate property doesn’t exist.
Optional chaining in JavaScript is very useful - we can access values without checking if the parent object exists. Instead of returning an error, it will return null or undefined.
The optional chaining ?. syntax has three forms:
obj?.prop – returns obj.prop if obj exists, otherwise undefined.
obj?.[prop] – returns obj[prop] if obj exists, otherwise undefined.
obj.method?.() – calls obj.method() if obj.method exists, otherwise returns undefined
Here's an example of a restaurant object on which we will check if a certain property exists or not with the help of Optional Chaining.
⚡To understand the concept better let's have a look at a few of the use cases.
Let's see what happens if we try to access a property that doesn't exist without the use of optional chaining.
We get an error. That’s the expected result. JavaScript works like this.
As restaurant.closingHours is undefined, an attempt to get restaurant.closingHours.mon.close fails with an error.
⚡To avoid this error, we first need to check if this property exists
The obvious solution would be to check the value using "if" or the conditional operator " ? " , before accessing its property.
It works, there’s no error. But it makes our code more unreadable and messier.
⚡Now, let's attempt to access the property by using optional chaining.
We see the code is short and clean, there’s no duplication at all.
Note: Only if the property that is before ?. that's "mon" here exists then this "close" property will be read and if not then immediately undefined will be returned.
Something “exists” here means if it’s not null and not undefined.
⚡Let's see one more example:
By using the ?. operator instead of just "." JavaScript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second.
If obj.first is null or undefined, the expression automatically short-circuits, returning undefined.
⚡ Combining with the nullish coalescing operator
In a nutshell, the nullish coalescing operator, written as ?? is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
Since the "city" property is not provided and evaluates to the undefined, the nullish coalescing operator then kicks in and defaults to the right-hand side operand "Unknown city" because the left-hand side operand is evaluated to undefined.
⚡ Optional chaining is invalid when used on the left-hand side of an assignment. This results in an error.
⚡Optional chaining with function calls
We can use optional chaining when attempting to call a method that may not exist.
For example, ?.() is used to call a function that may not exist.
Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found.
Optional chaining can also be used often when we are fetching responses from an API.
We may not be 100% sure if a certain object exists in our API response.
With optional chaining, we can check to see if something exists and handle an error gracefully.
That's all for this thread!
If you found it useful make sure to retweet it. 🔥😊
Uberduck.AI is a tool that allows you to make any text sound like it's been read by a celebrity or fictional character, and the results are incredible.
Check out these 10 amazing Dev Resources for you😎👇
1️⃣ Repl
Replit is a simple yet powerful online IDE, Editor, Compiler, Interpreter, and REPL. You can code right in your browser.
The second you create a new repl, it's instantly live and sharable with the world.
DevDocs combines multiple API documentations in a fast, organized, and searchable interface. Here you can find multiple developer documentation in a clean and organized web UI with instant search, offline support.