[JavaScript] What is Optional chaining (?.)?
![[JavaScript] What is Optional chaining (?.)?](https://cdn.hashnode.com/res/hashnode/image/upload/v1698343609547/13593ce6-30f7-46e2-a388-587208cce6b9.png)
The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.
Syntax
obj.val?.prop
obj.val?.[prop]
obj.func?.(args)
Examples
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah',
},
};
console.log(adventurer.dog.name);
// TypeError: Cannot read properties of undefined
console.log(adventurer.dog?.name);
// undefined
console.log(adventurer.someNonExistentMethod?.());
// undefined
Tips
Variables before
?.must be declared. The error occurs if the variable is not declared.console.log(user?.address); // ReferenceError: user is not definedDon't abuse optional chaining. Optional chaining should only be used for objects that do not need to exist.
If the left operand is
nullorundefined, the expression after?.will not be evaluated. (Short-circuiting)let user = null; let x = 0; user?.sayHi(x++); // Nothing happens console.log(x); // 0Optional chaining is not valid on the left-hand side of an assignment. But,
?.can be used in combination withdelete.delete user?.name; // Delete user.name if user exists user?.name = "Violet"; // SyntaxError: Invalid left-hand side in assignment // The error occurs because It is same with undefined = "Violet"
![[Design Pattern] What is MVVM?](https://cdn.hashnode.com/res/hashnode/image/upload/v1709803290305/c23a99a7-6b8d-4e55-8d1d-3db4d43cfe21.png)
![[React] What is Context API?](https://cdn.hashnode.com/res/hashnode/image/upload/v1708635890528/d079de98-8f99-4b9a-a2c6-26f5d30f0780.png)
![[React] Performance Optimization in Applications](https://cdn.hashnode.com/res/hashnode/image/upload/v1707425903425/75004fef-24ef-4471-8a00-5dcd5da67d73.png)
![[React] What is Controlled/Uncontrolled Component?](https://cdn.hashnode.com/res/hashnode/image/upload/v1707168528771/6c743a81-8fdf-47e5-a7de-5bf96f01ebe9.png)
![[React] What is Virtual DOM?](https://cdn.hashnode.com/res/hashnode/image/upload/v1707079605330/582fde11-0da2-47a3-b804-f942323bbd54.png)