Μετάβαση στο κύριο περιεχόμενο
← ⚡ JavaScript & the browser·Ενότητα C5 · Μάθημα 8
ΕργασίαGiven user = { profile: { name: "Anna", city: "", followers: 0 } }, log: (1) user?.profile?.city ?? "unknown" — should be empty string, not "unknown". (2) user?.profile?.followers ?? -1 — should be 0, not -1. (3) user?.missing?.deep?.value ?? "none" — "none".

Optional chaining ?. and nullish coalescing ??

100 XP7 min
Θεωρία

The two safe-access operators

These pair perfectly with the narrowing patterns from this module.

Optional chaining ?.

Short-circuits the whole chain to undefined if any intermediate is null or undefined.

user?.address?.zipCode;         // undefined if user or address is null
user?.greet?.();                // calls greet only if it exists
arr?.[0];                       // arr[0] only if arr is non-null

Nullish coalescing ??

Returns the right side only if the left is null or undefined. Unlike ||, it does NOT replace 0, "", or false — those are real values you usually want to keep.

const port = config.port ?? 3000;       // 0 stays 0
const name = user.nickname ?? user.name; // empty string nickname stays

Together

The canonical "safe pick with default" pattern:

const city = order?.shipping?.address?.city ?? "Unknown";

If any link is null/undefined → "Unknown". If shipping.address.city is "" or 0 → keeps it.

|| vs ??

x || y returns y for ANY falsy x — including 0, "", false. x ?? y only for null/undefined. In configs, ?? is almost always what you want.

🔒

Εγγράψου για να αρχίσεις να προγραμματίζεις

Η θεωρία είναι ανοιχτή για όλους. Ο επεξεργαστής, η ζωντανή προεπισκόπηση και ο έλεγχος ξεκλειδώνουν με 7-ήμερη δωρεάν δοκιμή — απαιτείται κάρτα.

Εγγραφή — δωρεάν δοκιμή →

Τα πρώτα 10 μαθήματα κάθε διαδρομής είναι δωρεάν. Δεν χρειάζεται κάρτα.

← ΠροηγούμενοΕπόμενο μάθημα →

Μια συμβουλή Python ή web την ημέρα — με email

Σύντομο, γραμμένο στο χέρι, χωρίς spam. Διαγραφή με ένα κλικ.