What is Optional Chaining?
Optional chaining is represented with
(?.)
and was introduced in ES62020.Optional chaining is used to access object properties; if we don't get a value, it returns
undefined
. After ?. this sign it helps to access properties if it's present and if it's not present it will return undefined.If there is a long chain of objects then it is useful too much because if we try to access an object just with
(.)
then if the object property value does not present it will throw an error. But if we try to access an object with optional chaining and if its properties don't present it will giveundefined
ornull
.If the value is other than
null
andundefined
if an object value is present it will return that value.If a value is guaranteed to not be nullish, then using
?.
to access properties on it is discouraged.
Let's understand with an example:
const person = {
name: "Nishtha",
age: 21,
experience: "fresher",
address: {
city: "Ahmedabad",
state: "Gujarat",
},
employed: true,
}
In the example, you can see a person's object created with different properties such as name, age, experience, address, and employed which holds some value, and in address, another object created with city and state.
While using optional chaining I am trying to access a property named cit it's showing undefined
because of the beautiful concept of optional chaining.
In the above example, trying to access property with (.)
which is not in the object it's showing an error.
This can be easily solved with optional chaining.
Conclusion:
Optional chaining is a safe and concise way to access the object values.
The optional chaining operator
?.
takes the reference to its left and checks if it is undefined or null.If its not able to find value then it will return
undefined
ornull
.