المعرفة:: JavaScript الحالة::مؤرشفة المراجع:: The Complete JavaScript Course 2022 From Zero to Expert
- Optional Chaining, introduced in ES2020, simply provides a way to access object properties and methods safely when that property value doesn’t exist (nullish values).
- If the property before the
?
exist, the value of the property before the?
will be read. If it is either zero or a string,undefined
is returned immediately to avoidTypeError: can't read property of undefined
. - Before Optional Chaining, we had to use if checks to ensure the object has the property before getting its value.
Examples
- Access day property dynamically, then open property with optional chaining, and at the same time use Nullish Coalescing Operator to set a default value.
- Call a method only if it exists, otherwise use Nullish Coalescing Operator to set another value.
- With arrays.