![]() |
VOOZH | about |
JavaScript Optional Chaining (ES2020) simplifies safe access to deeply nested object properties by preventing errors when values are null or undefined.
When working with deeply nested, tree-like object structures, developers must ensure intermediate properties exist to prevent runtime errors.
When we want to check a value of the property that is deep inside a tree-like structure, we often have to check whether intermediate nodes exist.
let Value = user.dog && user.dog.name;The Optional Chaining Operator allows a developer to handle many of those cases without repeating themselves by assigning intermediate results in temporary variables:
let Value = user.dog?.name;Syntax:
obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)
Note: If this code gives any error try to run it on online JavaScript editor.
Example: To demonstrate the implementation of the Optional Chaining with Object in JavaScript.
Example: To demonstrate the Optional Chaining with Function Call in JavaScript.