Insha Profile picture
28 Sep, 19 tweets, 4 min read
Hey there JavaScript Developers 👋

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. Image
⚡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. Image
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. Image
⚡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. Image
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. Image
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. Image
⚡ Optional chaining is invalid when used on the left-hand side of an assignment. This results in an error. Image
⚡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. Image
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. 🔥😊

Back to the Top👇

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Insha

Insha Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @Insharamin

30 Sep
With the evergrowing demand for Technical writing.

You can earn 1000$/ week. 💰📝

Let's know-how? 👇
⚡What is Technical Writing?

Technical writing is a writing discipline where you get to explain a particular topic to the audience in the easiest way possible!

If you've got a deep knowledge of something and want to amplify your voice- Technical writing is the way to go!
⚡There are a number of platforms that pay you well for writing 💰

Some of them are:

1- sitepoint.com
2- digitalocean.com
3- css-tricks.com
4- auth0.com
5- hasura.io
6- contentlab.io

And many more!
Read 9 tweets
18 Sep
8 Crazy Underrated Websites for Designers that you should know.

A Thread 👇
1️⃣ Wordmark

Wordmark helps you choose fonts by quickly displaying your text with your fonts.

📎 wordmark.it
2️⃣ Figside

Ship Websites with Figma.
Figside is perfect for personal websites, portfolio, landing pages and more.

📎 figside.com
Read 10 tweets
14 Sep
6 Underrated Websites that you should know.

A Thread 👇
1️⃣ Gifrun

With this tool, you can convert any video into a GIF format.

📎 gifrun.com
2️⃣ Uberduck

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.

📎 uberduck.ai/#mode=tts-basic
Read 8 tweets
7 Sep
Do you use Tailwind CSS?

Know these 5 websites to get Tailwind components pre-made🔥😎
1️⃣ Tailwind Components

A free repository for community components using TailwindCSS.
You can find Tailwind charts, grids, inputs, forms, templates, and much more.

📎tailwindcomponents.com
2️⃣ Tailblocks

Tailblocks shares handpicked Tailwind blocks, Tailwind templates, Tailwind Components, and other free resources related to Tailwind CSS.

📎tailblocks.cc
Read 7 tweets
4 Sep
Are you a Web Developer?

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.

📎replit.com
2️⃣ DevDocs

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.

📎devdocs.io
Read 12 tweets
1 Sep
Hey there JavaScript Developers 👋

Let's learn about some important Array Methods 😎👇
A little introduction about Arrays:

To store ordered collections, there exists a special data structure named Array in JavaScript.

Array elements are numbered, starting with zero. And it can store elements of any type.
Some of the Array Methods 👇

1️⃣ push()

The push() method adds a new element at the end of an array.
Read 17 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!

:(