VOOZH about

URL: https://www.geeksforgeeks.org/javascript/javascript-optional-chaining/

⇱ JavaScript Optional Chaining - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

JavaScript Optional Chaining

Last Updated : 12 Jan, 2026

JavaScript Optional Chaining (ES2020) simplifies safe access to deeply nested object properties by preventing errors when values are null or undefined.

  • Optional Chaining (ES2020) safely accesses properties or calls functions on null or undefined values.
  • Safely accesses nested properties without runtime errors.
  • Eliminates the need for explicit null or undefined checks.
  • Improves code readability and cleanliness.

Accessing Nested Properties with Optional Chaining

When working with deeply nested, tree-like object structures, developers must ensure intermediate properties exist to prevent runtime errors.

  • Missing properties can cause TypeError
  • Optional chaining helps safely access nested values

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;

Simplified Nested Access with Optional Chaining

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.

  • user.cat does not exist, so its value is undefined
  • Accessing .name on undefined throws a TypeError
  • Optional chaining (?.) prevents the error by safely returning undefined

Example: To demonstrate the Optional Chaining with Function Call in JavaScript.

  • user3.dog() causes a TypeError because dog does not exist on user3, so JavaScript cannot call it as a function.
  • Using optional chaining with function calls (user3.dog?.()) safely skips the call when the function is undefined, preventing the error.
Comment