Optional chaining is a feature introduced in ECMAScript 2020 (ES11) that allows you to access nested properties of an object without the need to explicitly check if each level of the nested property exists. It helps to avoid errors when trying to access properties of an object that may be undefined or null along the chain.
// Sample object
const user = {
name: 'John',
address: {
city: 'New York',
postalCode: '10001'
}
};
// Accessing nested property without optional chaining
const cityWithoutOptionalChaining = user.address.city; // 'New York'
// Accessing nested property with optional chaining
const cityWithOptionalChaining = user.address?.city; // 'New York'
// Accessing nested property that does not exist without optional chaining
const streetWithoutOptionalChaining = user.address.street; // undefined
// Accessing nested property that does not exist with optional chaining
const streetWithOptionalChaining = user.address?.street; // undefined
cityWithoutOptionalChaining
accesses thecity
property of theaddress
object without optional chaining, which works fine sinceuser.address
exists.
cityWithOptionalChaining
accesses thecity
property of theaddress
object using optional chaining (?.
). Ifuser.address
were undefined or null, it would return undefined instead of throwing an error.
streetWithoutOptionalChaining
attempts to access the non-existentstreet
property of theaddress
object without optional chaining, which results in undefined.
streetWithOptionalChaining
attempts to access the non-existentstreet
property of theaddress
object using optional chaining, which also results in undefined without throwing an error.
Related posts:
AMD Ryzen vs Apple M1 Processor: Performance, architecture, and other attributes
FOUR SIMPLE JAVASCRIPT TRICKS THAT WILL MAKE YOUR LIFE EASY IN 2022
Understanding GraphQL: Efficient Data Fetching for Modern APIs
How to implement Hash Tables & Hashing in JavaScript | In-Depth Guide for Data Structures &...