Skip to main content

JavaScript if Statement — exercises and bug fixes

5 hands-on exercises and 5 find-the-bug challenges for the JavaScript if Statement lesson. Every one is checked automatically in the browser — write the code, run it, and the tests tell you what still fails.

Exercises(5)

  1. 1

    Show a message when true

    easy10 min

    If age is 20, show "adult".

  2. 2

    Test a string value

    easy10 min

    If the role is "admin", show "allowed".

  3. 3

    Check an empty list

    easy10 min

    If the cart has no items, show "empty".

  4. 4

    Combine two conditions

    easy10 min

    If the user is logged in AND verified, show "welcome".

  5. 5

    Guard against a missing value

    medium10 min

    Only show the name when it is present; here it is "Sam".

Find the bug(5)

  1. 1

    Fix the assignment in the condition

    easy8 min

    A single = makes this condition always run.

  2. 2

    Fix the inverted condition

    easy8 min

    The branches sit on the wrong side of the test, so a 20-year-old is labelled a minor.

  3. 3

    Fix the loose equality

    easy8 min

    Loose equality lets a string match a number.

  4. 4

    Fix the misplaced semicolon

    easy8 min

    A semicolon right after if() ends the statement early.

  5. 5

    Fix the wrong logical operator

    easy8 min

    OR is used where both conditions must hold.

Ready to write the code?

The editor, the automatic checks and the worked solutions open up with an account.

Open the workspace