JavaScript lesson · 15 min

JavaScript Conditionals

Make decisions with if, else if, and else so code can react to different situations.

Code runs locally in your browser

What you will practice

  • Write an if statement.
  • Handle multiple branches with else if.
  • Choose messages based on a value.

What this means

A conditional lets your program choose between paths. Instead of always doing the same thing, the code checks a condition and runs the matching block.

The condition inside `if (...)` becomes either true or false. If it is true, that block runs. If it is false, JavaScript tries the next `else if` or `else` block.

Conditionals are how interfaces react: show an error, enable a button, choose a badge, or decide whether a user can continue.

If this is your first time seeing this

A conditional lets code make a choice. It asks a yes/no question and runs the matching block.

Read `if (score >= 90)` as: if the score is at least 90, do the code inside these braces.

Mini glossary

Condition
An expression that becomes true or false.
Branch
One possible path through an if/else statement.
Comparison
Checking values with operators like `>`, `<`, `>=`, or `===`.

Example from everyday life

A conditional is like a traffic light rule. If the light is green, go. Else if it is yellow, slow down. Else, stop. The action depends on the situation.

How it works step by step

  1. The code starts with a score of `82`.
  2. JavaScript checks whether the score is at least `90`; it is not, so that branch is skipped.
  3. It checks whether the score is at least `75`; this is true, so the grade becomes `B`.
  4. A second conditional chooses a message based on the final grade.

Where you will use this

  • A form shows a validation message only when an input is invalid.
  • A dashboard colors a metric green, yellow, or red depending on the number.
  • A checkout flow blocks payment until required fields are complete.

Before you run the code

Conditionals are about control flow: deciding which code should run next.

Good conditional code reads like a small rulebook. Each branch should be specific enough that the next person can understand the decision.

Common beginner mistakes

  • Using one `=` instead of `===` when comparing values.
  • Putting the broadest condition first, so later specific branches never run.
  • Forgetting the fallback `else` case.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingChooses the correct grade branch
WaitingChooses the matching message

Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Change the score to `95` and predict the grade.
  • Change the score to `60` and see the fallback branch.
  • Add a new branch for scores greater than or equal to `50`.