The JS Bifrost — Optional Chaining Operator(?.)
Simple and Easy access to nested object properties…
Welcome to the world of The JS Bifrost, you are going deep into enlightened the world of JavaScript. This is the next article in the series. We will discuss about newly introduced operator in JavaScript — “Optional Chaining”.
What happens when we deal with -
Data — Easy to traverse.
Nested Data — Little difficult to traverse.
More levels of Nesting in Data — Painful to traverse; More lines of code.
Ahhh…. too much work ???😰
Hang in there. OPTIONAL CHAINING to your rescue !!!
Optional Chaining operator has been introduced in JavaScript now and is included in ES2020.
What is an Optional Chaining( ?. ) ??
Optional Chaining is a new feature of JavaScript which helps to easily access properties of nested Objects.
Optional chaining is implemented using combination of ?(question mark) and .(dot) operators.
Before going deep into implementation of Optional Chaining, let us understand null and undefined concepts for clear understanding of Optional Chaining Operator.
Consider example of player
Object
let player = {id: 1234567,name: "AMBUSHER",tag: null}
null :
null
value means no value which is mentioned as “null” word. The “” (blank string) or space are not null values. Record or field which has entered nothing (leaved it as blank) is a null value.
e.g tag
property is a null
undefined :
undefined
means the property, object or value which is not defined or not present.
e.g rewards
is undefined
property which is not present in player
Object
Now, we know null
and undefined
, let us see how to use it.
How to use??
Using ?.
operator, we can traverse through deeply nested Objects.
There are 3 syntaxes:
1. obj?.property
Returns property of obj
, if obj
exist, otherwise returns null or undefined.
2. obj?.[property]
This syntax works just like the first syntax but in this case, property should always be mentioned in square bracket with double(“propName”) or single(‘propName’) quotes.
3. obj?.method()
Calls method() of obj
, if obj
exist, otherwise returns null or undefined.
We can write this syntax as obj.method?.()
also.
Now that we are familiar with the syntax of Optional Chaining, let’s understand it’s validation step by step:
- If object is not present then it will return as undefined.
2. If object is mentioned as null
then output gives null.
3. If object is exist, then it checks that whether property of an object is null or undefined. If property isn’t undefined or null, then it returns value of property or call of method.
As we have seen all ways to use Optional Chaining operator( ?.
), let us understand how it works..??
How it works??
Optional Chaining operator checks if object before ?.
operator is null or undefined.
If object isn’t null or undefined then it will check for property of object mentioned after ?.
operator. If it is valid then it will return value of property, otherwise null or undefined.
Using obj?.property
Syntax
Consider an example of employee
object which has properties id, name, address(includes city, state, country).
Consider an above employee
object for below examples.
In the above example, it checks if employee
object is null
or undefined
. If passed, it will check for next property after ?. operator, otherwise it will return null
or undefined
based on its value.
Example 1:
In an example 1, checks if employee
object is present. As it is present here, it will proceed and check for name
property which as well available. Then output will be value of name
property that is “Glee”.
Example 2:
In an example 2 , first checks employee
object is present or not, it is present, so it checks for address property/object which is again present there, then it checks for city property which is not entered by user(that means city is vacant). That’s why it returns as null
.
Example 3:
In an example 3, this works as previous one, first checks for employee object and then checks for address property or object and then checks for pinCode property which is not defined in address object. That’s why it returns as undefined.
As of now, we have seen how to implement Optional Chaining, isn’t it far more simple than we thought…??🤗
Let’s see implementation of other 2 syntaxes…
Consider an example of player
Object which has properties like id, name, tag, status(which includes rank and level properties).
Example
Output:
In the above example, we used all 3 syntaxes, Lets understand one by one.
player?.tag
In a first case, player
object exists, so it checks for tag
property of player object. tag property is defined but it is null(not assigned any value). That’s why it returns as null.
player?.["name"]
In a second case, property is mentioned in square bracket [] with double quotes(“”). Here, player
object exists and name property is also available with value “Ambusher”. Then it returns as Ambusher.
player.someNonExistingMethod?.()
In a third case, we use method as property and calls the method. Here, first checks availability of player
object and then checks for someNonExistingMethod()
named property which is not defined. That’s why it returns as undefined.
We can write above statement as player?.someNonExistingMethod()
also. It will give same result as above statement.
If method() is defined in object and we are accessing it by
player.methodName?.()
orplayer?.methodName()
, then it will execute.
How to access nested object properties
In the above case, we can access rank
as player?.status?.rank
or player.status?.rank
and it will return rank value that is “Ace”.
As we have seen implementation of all types of syntaxes and it’s really simple to understand and easy to implement. Still if you don’t have clear picture of Optional Chaining, let’s see it diagrammatically…
The above flowchart shows clear picture of Optional Chaining. If obj isn’t null or undefined, only then it can proceed for property checking. It works same for nested objects.
Now that we have understood the Optional Chaining operator in depth, hope you find it simple and easy to implement.
Conclusion
Optional Chaining is simple and easy way to traverse complex nested objects by using?.
operator. Question mark ? and full stop . makes things sorted as always and it happens with Optional Chaining also😄.
Sometimes problem seems more complex and difficult but when we go into it, it goes easier than what we think and we make it possible. Definitely we get solution NO MATTER HOW COMPLEX THE PROBLEM IS…
If you enjoyed reading this article, please share :) Thank you.
Explore “The JS Bifrost” for series of more JavaScript articles!!!
References
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining