EasyModern JS📖 Theory Question

What is optional chaining (?.) and nullish coalescing (??)?

💡

Hint

?. short-circuits on null/undefined; ?? fallbacks only for null/undefined

Full Answer

// Optional chaining
const city = user?.address?.city;
const name = users?.[0]?.name;
const val = obj?.method?.();

// Nullish coalescing — fallback for null/undefined ONLY
const count = user.count ?? 0;
// if count=0, result is 0 (correct!)
// vs OR operator:
const bad = user.count || 0;
// if count=0, bad=0 but for wrong reason (0 is falsy)
💡 Use ?? when 0, '', false are valid values. Use || for general falsy fallbacks.

More Modern JS Questions

MediumWhat are generators and when would you use them?EasyWhat are tagged template literals and what are they used for?EasyExplain destructuring for objects and arrays — including defaults, renaming, rest, and nesting.EasyWhat are Symbols and what are their main use cases?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint