Lesson 2 of 8
Guard clauses
- 12 min
- 6 checks
- 3 hints
- Go to task
Goal
Return early instead of nesting conditions
Explanation
A function with four nested conditions is hard to read, and it hides the cases you haven't handled.
The alternative is the guard clause: you check for each abnormal case at the top of the function and return right away, so the normal path stays at the top level with no extra indentation.
The real benefit isn't how it looks. It's that the abnormal cases become visible and lined up at the top of the function, so you notice the ones you forgot.
Your task
Rewrite priceLabel with guard clauses, handling a missing value, a value that isn't a number, a negative number, and zero.
Checks
6 checks- The function is defined
- A missing value gives "Unavailable"
- Non-numbers and negative numbers are rejected
- Zero gives "Free", not "0 SAR"
- A positive number gives "25 SAR"
- The guards are at the top level, not nested