Optional chaining is a new feature introduced in JavaScript (JS) since version ES2020. This feature simplifies accessing properties or methods of an object that may not exist or be empty.
Before optional chaining, when we wanted to access a property or method of an object, we usually had to check if the object existed or not. If it didn't exist, we had to use conditions to avoid errors. This led to writing long, hard-to-read, and complex code.
Optional chaining helps us solve this problem by allowing us to access properties or methods in a chain without having to check each step. If a step in the chain doesn't exist or is empty, optional chaining will return undefined instead of causing an error.
The syntax of Optional chaining is .?
Here is an example illustrating how to use optional chaining in JS:
const user = {
name: 'John',
address: {
city: 'New York',
street: '123 Main Street'
},
hobbies: ['reading', 'painting']
};
// Truy cáºp thuá»™c tÃnh name của đối tượng user
console.log(user?.name); // Output: 'John'
// Truy cáºp thuá»™c tÃnh không tồn tại
console.log(user?.age); // Output: undefined
// Truy cáºp thuá»™c tÃnh của đối tượng con
console.log(user?.address?.city); // Output: 'New York'
// Truy cáºp phÆ°Æ¡ng thức của đối tượng
console.log(user?.hobbies?.join(', ')); // Output: 'reading, painting'
// Truy cáºp phÆ°Æ¡ng thức không tồn tại
console.log(user?.getFullName?.()); // Output: undefined
As you can see in the example above, we use the ?. operator to access properties or methods of the user object. If a step in the chain doesn't exist, the result will be undefined.
Optional chaining helps us write shorter and more readable code. It also reduces the chance of errors when accessing properties or methods of an object.