ECMAScript question detail
Optional chaining
In JavaScript, Long chains of property accesses is quite error-prone if any of them evaluates to null or undefined value. Also, it is not a good idea to check property existence on each item which in turn leads to a deeply-nested structured if statements.
Optional chaining is a new feature that can make your JavaScript code look cleaner and robust by appending(?.) operator to stop the evaluation and return undefined if the item is undefined or null. By the way, this operator can be used together with nullish coalescing operator to provide default values
let vehicle = {
};
let vehicle1 = {
car: {
name: 'ABC',
speed: 90
}
};
console.log(vehicle.car.name); // TypeError: Cannot read property 'name' of undefined
console.log(vehicle.car?.name); // Undefined
console.log(vehicle.car?.speed); // Undefined
console.log(vehicle1.car?.name); // ABC
console.log(vehicle1.car?.speed); // 90
console.log(vehicle.car?.name ?? "Unknown"); // Unknown
console.log(vehicle.car?.speed ?? 90); // 90