Command Palette

Search for a command to run...

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

Guard clauses keep the main rule flat

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?

Guard clauses keep the main rule flat

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Shipping: 0
Shipping: 500
Shipping: 100
TypeError: shippingCost needs an order