Language 6 of 10 · Topic 0.4

Operators, Optional Chaining (?.) & Nullish Coalescing (??)

1Concept

Nullish coalescing ?? falls back ONLY on null or undefined (unlike || which treats 0, '', and false as falsy). Optional chaining ?. short-circuits to undefined without throwing errors.

2Architecture Diagram

val = 0 || 10;  ──► Returns 10 (because 0 is falsy)
val = 0 ?? 10;  ──► Returns 0 (because 0 is not null/undefined!)

3Code Example

Stage 0 Language Foundations
const config = {
    port: 0,
    user: {
        profile: {
            name: "Alex"
        }
    }
};

const portOR = config.port || 3000;
const portNullish = config.port ?? 3000;

console.log(`Port with ||: ${portOR}`);
console.log(`Port with ??: ${portNullish}`);
console.log(`Optional Chaining: ${config?.user?.profile?.name}`);
console.log(`Missing property: ${config?.user?.avatar?.url}`);

4Expected Output

Port with ||: 3000
Port with ??: 0
Optional Chaining: Alex
Missing property: undefined

5Key Takeaways

  • Use ?? instead of || when 0, '', or false are valid values.
  • ?. safely navigates deeply nested properties without try/catch.
  • ?.[index] works for array indexing.