Skip to main content

JavaScript Optional Chaining Operator (Live Playground)

In this tutorial, we will explore the optional chaining operator, and learn how to use it in our code.

Optional Chaining Operator (?.)

The optional chaining operator allows you to access the properties of an object without throwing an error if the object or one of its properties is null or undefined.

Example:

const user = {
name: 'John',
address: {
city: 'New York',
country: 'USA',
},
};

const city = user?.address?.city;
console.log(city); // Output: 'New York'

In the example above, even if the address property was null or undefined, accessing the city property using the optional chaining operator would not throw an error.

Live Playground, Try it Yourself

Conclusion

Understanding and using the optional chaining operator is essential for writing efficient and concise code in your JavaScript programs.