# Modern Syntax: Optional Chaining & More — JavaScript Fundamentals: From Syntax to Async

Source: https://www.geekswithgeeks.com/en/javascript/js-modern-syntax

> Write safer, shorter code with optional chaining, nullish assignment, at(), structuredClone and private class fields.

## Optional chaining

`?.` stops and returns `undefined` when something is `null` or `undefined`, and pairs well with `??`.

```javascript
const user = { profile: null };
console.log(user.profile?.name);          // undefined, no error
console.log(user.profile?.name ?? "Guest"); // "Guest"
user.settings ??= { theme: "dark" };       // assign only if nullish
```

## Handy newer APIs

`at()` reads from the end, `structuredClone` deep-copies, and `#private` fields hide class internals.

```javascript
const arr = [10, 20, 30];
console.log(arr.at(-1));                 // 30
const copy = structuredClone({ a: { b: 1 } });

class Account {
  #balance = 0;
  deposit(n) { this.#balance += n; }
  get balance() { return this.#balance; }
}
```

Use `?.` to guard optional data, not to hide real bugs. Use `structuredClone` instead of `JSON.parse(JSON.stringify(x))` for deep copies.

Quick check

**Quiz:** What does user.profile?.name return when profile is null?

- [x] undefined
- [ ] A TypeError
- [ ] null
- [ ] ""

*Answer:* undefined. Optional chaining short-circuits to undefined.
