Lesson 2 of 8

Guard clauses

Goal

Return early instead of nesting conditions

01

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.

02

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
  1. The function is defined
  2. A missing value gives "Unavailable"
  3. Non-numbers and negative numbers are rejected
  4. Zero gives "Free", not "0 SAR"
  5. A positive number gives "25 SAR"
  6. The guards are at the top level, not nested
03

Hints

0/3
Track lessons0 of 8 done

Learn how to read an error message, check inputs before you use them, and catch the errors worth handling.

Intermediate level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Learn how to read an error message, check inputs before you use them, and catch the errors worth handling.

Intermediate level, 8 lessons, 1.5 hours in total.