LESSON 09 · BEGINNER4 min read

Conditionals & Guard Clauses

Choose between branches with if, else if, and switch, then keep calculations safe with early exits and validation.

ES2024 / Node.js 20+Free to readModule 2 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Write if, else if, and else branches in a deliberate order.
  • Use a ternary for a short two-value choice.
  • Apply guard clauses to validate input before calculation.
  • Recognize common logic mistakes with switch and nested conditions.

01if runs a block when a condition is truthy

An if statement runs a block when its condition is truthy. The condition goes in parentheses and the block goes in braces. Use braces even for one line; they make later edits safer. An optional else block runs when the condition is falsy.

Conditions are ordinary expressions. A comparison produces a boolean, but a string or number can also be tested for truthiness. Prefer explicit comparisons when zero, an empty string, or a missing value should be treated differently. For example, write count === 0 when only the number zero should match, rather than relying on its falsiness.

pass-check.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02else if checks alternatives in order

else if lets you test a sequence of alternatives. JavaScript checks from top to bottom and runs only the first matching branch. Order matters: a broad condition placed first can hide a more specific one below it.

The final else is the fallback for values that matched nothing. Keep branches mutually understandable. If a reader has to simulate three conditions to see which one wins, rewrite the sequence or use a guard clause.

grade.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03A ternary chooses one of two values

A ternary expression chooses one of two values: condition ? valueWhenTrue : valueWhenFalse. Use it when both outcomes are short expressions that fit naturally on one line. Do not nest ternaries to encode a long decision tree; an if/else chain is easier to review.

A ternary is an expression, so it can appear inside a template literal or an assignment. It is not a statement. If you need side effects in each branch, use if/else instead. The goal is clarity, not the shortest possible line.

member-price.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04Guard clauses keep the main path flat

A guard clause checks a bad or impossible case first and exits early. In a function, that usually means returning a message or a default before the main calculation. The main path then stays unindented and easy to read. The function wrapper here is only a way to reuse the checks; the guard clauses are the new idea.

Guards are especially useful for validation. Check that required values exist and have the right type before dividing, indexing, or formatting. A clear rejection is better than a surprising NaN or a crash deep inside a calculation. An early exit also avoids nesting the successful path inside several layers of else blocks.

shipping.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

05switch and common logic mistakes

A switch statement compares one value against several cases using strict equality. Each case ends with break unless you intentionally want execution to continue into the next case. The default case handles everything else.

Common mistakes include using = instead of ===, forgetting break, and ordering conditions so a later branch can never run. Read each branch aloud as a rule. If two rules overlap, decide which one should win and make that order obvious. A short comment above an unusual fallthrough can save a future reader from removing it by accident.

plan.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • if/else if chains stop at the first matching branch, so order communicates priority.
  • Use ternaries for short value choices and if/else for longer decision logic.
  • Guard clauses validate early and keep the successful path flat and readable.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Apply ticket price rules

With age = 70 and isMember = true, set price to 5 when age is under 12, to 7 when age is 65 or older, and otherwise to 10 for a member or 14 for a non-member. Print the final price.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
const age = 70;const isMember = true;let price;if (age < 12) {  price = 5;} else if (age >= 65) {  price = 7;} else {  price = isMember ? 10 : 14;}console.log(price);

The output is 7. The senior rule matches before the member branch, so age 70 receives the senior price even though the person is also a member.

02

Exercise 2: Validate before calculating

Convert hoursText = "8" with Number and multiply it by rate = 25. If the conversion is NaN or the hours are negative, print Invalid hours; otherwise print Pay: followed by the result. Then repeat the check with the text "eight" so the invalid path also runs.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
const rate = 25;const validHours = Number("8");if (Number.isNaN(validHours) || validHours < 0) {  console.log("Invalid hours");} else {  console.log(`Pay: ${validHours * rate}`);}const invalidHours = Number("eight");if (Number.isNaN(invalidHours) || invalidHours < 0) {  console.log("Invalid hours");} else {  console.log(`Pay: ${invalidHours * rate}`);}

The first conversion produces 8 and prints Pay: 200. The second produces NaN, so the guard branch prints Invalid hours instead of multiplying.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01Why does the order of an if/else if chain matter?
02When is a ternary a good choice?
03What does a missing break at the end of a switch case usually cause?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Apply ticket price rules

With age = 70 and isMember = true, set price to 5 when age is under 12, to 7 when age is 65 or older, and otherwise to 10 for a member or 14 for a non-member. Print the final price.

EXPECTED OUTPUT
7
main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.