Lesson 40 / 40
Modern Syntax: Optional Chaining & More
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 ??.
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 nullishHandy newer APIs
at() reads from the end, structuredClone deep-copies, and #private fields hide class internals.
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
Quick check: What does user.profile?.name return when profile is null?
- undefined
- A TypeError
- null
- ""
Answer
undefined — Optional chaining short-circuits to undefined.