# Optional Chaining

Optional chaining (`?.`) is a safe way to access nested object properties, even if an intermediate property doesn't exist. If the property before `?.` is `undefined` or `null`, the expression short-circuits and returns `undefined` instead of throwing an error.

## 1. The Problem

Before optional chaining, accessing a deeply nested property required checking every level to avoid `TypeError: Cannot read properties of undefined`.

```javascript
const user = {};

// Error! user.address is undefined
// console.log(user.address.street); 

// The old way (verbose)
const street = user.address && user.address.street;
console.log(street); // undefined
```

## 2. The Solution (`?.`)

With optional chaining, you can simplify this check.

```javascript
const user = {};

const street = user.address?.street;
console.log(street); // undefined (no error)
```

If `user.address` exists, it proceeds to access `.street`. If `user.address` is `null` or `undefined`, it stops immediately.

## 3. Syntax Variations

### Object Properties
```javascript
obj?.prop
obj?.[expr]
```

### Arrays
```javascript
const arr = null;
const item = arr?.[0]; // undefined
```

### Function Calls
Useful if an API might not return a method you expect.

```javascript
const user = {
  admin() {
    console.log("I am admin");
  }
};

user.admin?.(); // "I am admin"
user.guest?.(); // undefined (no error)
```

## 4. Short-Circuiting

If the left-hand side is nullish, the right-hand side is **not evaluated**.

```javascript
let x = 0;
const obj = null;

obj?.[x++]; // x is not incremented because obj is null

console.log(x); // 0
```

## 5. Combining with Nullish Coalescing

Optional chaining is often used with the Nullish Coalescing Operator (`??`) to provide a default value if the chain is broken.

```javascript
const user = {};
const street = user.address?.street ?? "Unknown Street";

console.log(street); // "Unknown Street"
```

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/es6-features]]