Optional Chaining (?.) Vs Ternary Operator (?)
TD; LR Both Optional Chaining and Ternary Operator have their own importance in JavaScript. Undoubtedly, both have some similar syntax but not 100%.
Basic Overview
- Optional chaining was introduced in ECMA script 2020 commonly known as ES11. It is used to simply access properties in an array or objects.
- A Ternary Operator is an operator that performs an operation when a certain condition is true.
Ternary Operator
The ternary operator is a shorthand way to write an if-else statement with the help of this we can write if-else logic with simpler and more shorter syntax.
The ternary operator is denoted by?
- For better understanding let's take an example, suppose we have to write code that checks if a user is eligible to vote or not in a traditional way i.e. if-else statement we were writing code like this:
Now we will write the same code with the help of a ternary operator
Syntax:
condition ? Code statement 1 : Code Statement 2;Here if the condition is true then code statement 1 will be executed and if the condition becomes false then code statement 2 will be executed.
Here we have taken the same example i.e. if a user is eligible to vote or not but here we have used the ternary operator and we can see clearly that the ternary operator makes the code much smaller. In this case `eligible to vote` will logged in the console.
Get Simarjot Singh’s stories in your inbox
Join Medium for free to get updates from this writer.
But to note the ternary operator’s code can be complex if we have nested statements.
Optional Chaining
Optional Chaining is another wonderful concept of javascript that was released in ECMA 2020.
This operator helps us to write clean and simple code for retrieving data from objects and arrays.
For better understanding lets have an example:
We have an object name obj in that we have 2 properties named name and age now, if we want to access any property of obj we have 2 ways and traditional way using if-else statement and another way is using optional chaining :-
Traditional Way
Now we have to use the nested if-else statement to get the name property of obj. Here, firstly we check if obj exist or not if it exists it will check if the property name exists or not if it exists then it will console its value otherwise it will console name not found if obj does not exist it will console obj not found .
Modern Approach using Optional Chaining
Now it will check if the obj exists it will check for the name property if it exists it will console its value otherwise undefined if you want to add some statement instead of undefined then you can use Null Coalescing Operator(??)
Conclusion
- Using optional chaining it can be easy to access properties of obj or element of the array without causing the error.




