# [JavaScript] What is Optional chaining (?.)?

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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) or [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null), the expression short circuits and evaluates to [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) instead of throwing an error.

### Syntax

```javascript
obj.val?.prop
obj.val?.[prop]
obj.func?.(args)
```

### Examples

```javascript
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

1. Variables before `?.` must be declared. The error occurs if the variable is not declared.
    
    ```javascript
    console.log(user?.address);
    // ReferenceError: user is not defined
    ```
    
2. Don't abuse optional chaining. Optional chaining should only be used for objects that do not need to exist.
    
3. If the left operand is `null` or `undefined`, the expression after `?.` will not be evaluated. (Short-circuiting)
    
    ```javascript
    let user = null;
    let x = 0;
    
    user?.sayHi(x++); // Nothing happens
    
    console.log(x); 
    // 0
    ```
    
4. Optional chaining is not valid on the left-hand side of an assignment. But, `?.` can be used in combination with `delete`.
    
    ```javascript
    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"
    ```
