Optional Chaining
The optional chaining (?.
) operator simplifies comparing multiple data properties in a chain of connected objects. This is especially valuable if any of the properties are null
, as the operator will return undefined
instead of throwing an error.
Optional chaning can be used to validate nested object properties, call optional functions or methods on optional objects, accessing array elements, and more.
The primary benefits of using optional chaining instead of regular syntax include simplifying the code to achieve the same result, making it easier to read, protecting against runtime errors, and enhancing maintainability.
Syntax
The basic syntax for using optional chaining is as follows:
// To access an object property
object?.property;
//To access an element in an array
array?.[index];
//To invoke a function (if it exists)
object?.method?.();
Examples
Accessing Object Properties
To search for the state
object of person
:
const person = {name: 'Alice',gender: 'Female',age: 12,address: {street: '1111 Palm Ave',city: 'Broken Arrow',state1: 'Oklahoma',},favoriteFoods: ['pizza', 'ice cream', 'cake'],commonPhrase: function () {return `${this.name} always says "I love ${this.address.state1}."`;},};// Regular syntax for checking if the state1 property existsconst state1Regular = person && person.address && person.address.state1;console.log(`State (regular syntax) is: ${state1Regular}`);// This can be rewritten as:const state1Chaining = person?.address?.state1;console.log(`State (optional chaining) is: ${state1Chaining}`);
The output of the above code will be as follows:
State (regular syntax) is: OklahomaState (optional chaining) is: Oklahoma
Accessing Array Elements
To search for the cake
in the favoriteFoods
array of person
:
const person = {name: 'Alice',gender: 'Female',age: 12,address: {street: '1111 Palm Ave',city: 'Broken Arrow',state1: 'Oklahoma',},favoriteFoods: ['pizza', 'ice cream', 'cake'],commonPhrase: function () {return `${this.name} always says "I love ${this.address.state1}."`;},};// Regular Syntax for searching favorite foodconst foodRegular =person &&person.favoriteFoods &&person.favoriteFoods.find((item) => item === 'cake');console.log(`Favorite Food (regular syntax) is: ${foodRegular}`);// This can be rewritten as:const foodChaining = person?.favoriteFoods.find((item) => item === 'cake');console.log(`Favorite Food (optional chaining) is: ${foodChaining}`);
The output of the above code will be as follows:
Favorite Food (regular syntax) is: cakeFavorite Food (optional chaining) is: cake
Accessing Object Functions
To determine if the commonPhrase
function exists in person
before invoking it:
//Regular Syntaxif (person && typeof person.commonPhrase === 'function') {const phrase = person.commonPhrase();console.log(`${phrase}`);}//This can be rewritten as:const phrase = person?.commonPhrase?.();console.log(`${phrase}`);
The output of the above code will be as follows:
Alice always says "I love Oklahoma."Alice always says "I love Oklahoma."
Codebyte Example
Run the following example and compare the regular syntax of conditional statements and optional chaining on a more complex data set:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours