|

Day 32 of 100: Optional Chaining and Nullish Coalescing — Crash-Proof Access

Day 32 of 100 — 100 Days of Playwright with TypeScript Challenge. Phase: JavaScript Fundamentals. JavaScript (Days 1-33) → TypeScript (Days 34-63) → Playwright (Days 64-96) → AI Framework Capstone (Days 97-100).

🎭 Want to master this with real projects? Join the Playwright Automation Mastery course at The Testing Academy.


API responses have missing fields. Deep access crashes. Two operators fix it: ?. and ??

Contents

Optional Chaining ?.

const res = { user: { profile: null } };

// res.user.profile.city          → TypeError: cannot read 'city'
res.user?.profile?.city;          // undefined — no crash
res.user?.addresses?.[0];         // optional array access
res.user?.getName?.();            // optional method call

🚀 Level Up Your Playwright

From locators to CI pipelines — build a production-grade Playwright + TypeScript framework step by step.

Nullish Coalescing ??

const config = { retries: 0, timeout: null };

// || treats 0 as falsy — WRONG for numeric config:
config.retries || 3;              // 3 — but user explicitly set 0!

// ?? only triggers on null/undefined:
config.retries ?? 3;              // 0 — correct
config.timeout ?? 30000;          // 30000 — null replaced
config.missing ?? 'default';      // 'default'

Combined Pattern

// Safe deep read with default — the API-response idiom:
const city = res.user?.profile?.address?.city ?? 'UNKNOWN';

// In assertions, prefer explicit checks:
// expect(body.user?.email).toBeDefined();   — clear failure message

Tomorrow (Day 33): JS capstone — a pure-JavaScript API test suite.

🎓 Master Playwright End to End

Join hundreds of SDETs building real automation frameworks. Lifetime access, hands-on projects, and a job-ready portfolio.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.