Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 13.5 — Defensive Coding
JavaScript · Example 2 of 4 ES2020+

Optional chaining and ?? on messy data

|| replaced Asha's real volume of 0 with 50. ?? only replaces null and undefined.

Defensive code checks what comes in before using it: guard clauses reject bad input at the top of a function, optional chaining and ?? handle values that may be missing, and anything unexpected fails loudly instead of quietly producing wrong results.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Rewrite with guard clauses so that null throws a TypeError and an empty name returns "Hello, guest": function greet(user) { if (user) { if (user.name) { return "Hello, " + user.name; } else { return "Hello, guest"; } } }

02

Write discountedPrice(price, percent) that throws a TypeError unless both are finite numbers, throws a RangeError unless percent is between 0 and 100, and returns the price after the discount. Show the result for (200, 10) and the error for (200, 150).

Explain it without notes

01

What is a guard clause, and why do many developers prefer it to nested if statements?

02

What is the difference between ?? and ||, and when does it matter?

03

What is a silent failure? Give two examples and how to avoid them.

04

Where should you validate data, and why there?

Optional chaining and ?? on messy data ES2020+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Asha | Pune | with ||: 50 | with ??: 0
Ravi | Unknown city | with ||: 50 | with ??: 50
Meera | Unknown city | with ||: 50 | with ??: 50
greet result: undefined