Find a course

Module 1: Game State and RulesLesson 2 of 1112 min

If Statements and Game Rules

Turn game rules into code with if, else if and else, compare values with comparison operators and combine conditions with and, or and not.

Step 1 of 11Learn

Rules are conditions

Every game is a set of rules. If you touch lava, you lose a life. If your lives reach zero, the game is over. If you collect 100 coins, you get an extra life. In code, each rule becomes an if statement:

if (lives === 0) {
  isGameOver = true;
}

The part in parentheses is the condition. It's an expression that's either true or false. If it's true, the code inside the curly braces runs. If it's false, JavaScript skips it.

To build conditions, you compare values with comparison operators:

OperatorMeaningExample
===is equal tolives === 0
!==is not equal tolevel !== 5
>greater thanscore > 100
<less thantime < 10
>=greater than or equalcoins >= 100
<=less than or equalhealth <= 0

Remember: one = stores a value, three === compares. Writing if (lives = 0) doesn't compare at all; it sets lives to 0, which is one of the most famous bugs in programming. JavaScript also has == (two signs), but it converts types in surprising ways, so stick with ===.

How an if statement runs: the condition lives === 0 is checked; if true, the code in the braces runs; if false, JavaScript skips it and continueslives === 0 ?truefalseisGameOver = true;skip the bracescontinue with the next line

Step 2 of 11Practice · Match the pairs

Match each game rule to the condition that checks it.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. The player has no health left
  2. The player reached at least 100 coins
  3. Fewer than 10 seconds remain
  4. The player is not on level 1
  5. The score is exactly 500

Step 3 of 11Learn

else and else if

Often you want one thing to happen if a condition is true and something else if it's false. That's else:

if (score >= 1000) {
  message = "You win!";
} else {
  message = "Try again!";
}

For more than two outcomes, chain conditions with else if. JavaScript checks them from top to bottom and runs only the first one that's true:

if (score >= 1000) {
  medal = "gold";
} else if (score >= 500) {
  medal = "silver";
} else if (score >= 100) {
  medal = "bronze";
} else {
  medal = "none";
}

A score of 750 fails the first check, passes the second and gets silver. The third check is never even looked at.

Order matters a lot here. If you put score >= 100 first, then a score of 750 would pass it and get bronze, and the silver and gold branches could never run. When conditions overlap, put the strictest one first.

Step 4 of 11Practice · Choose one

Using the medal code above, what medal does a score of exactly 500 earn?

Step 5 of 11Practice · Diagram

An else-if chain is checked top to bottom

JavaScript stops at the first condition that is true. Tap each step.

Where does a score of 120 stop?

Tap the shape that answers the question, then press Check.

An else-if chain is checked top to bottomProcess diagram: score >= 1000 → gold → score >= 500 → silver → score >= 100 → bronze → else → none.score >=1000 → goldscore >= 500→ silverscore >= 100→ bronzeelse → none
score >= 1000 → gold

Checked first. 750 fails here.

score >= 500 → silver

Only reached if the first test failed. 750 and 500 stop here.

score >= 100 → bronze

Only reached if both tests above failed.

else → none

Runs when nothing above was true.

Step 6 of 11Learn

Combining conditions

Real rules often depend on more than one thing. JavaScript has three logical operators:

  • && (and): true only if both sides are true. hasKey && atDoor opens the door only when the player has the key and is standing at the door.
  • || (or): true if at least one side is true. health <= 0 || time <= 0 ends the game if either runs out.
  • ! (not): flips true and false. !isPaused is true when the game is not paused.
if (!isPaused && lives > 0) {
  updateGame();
}

This runs the game only while it isn't paused and the player is still alive.

A common mistake is writing English-style shortcuts. if (key === "a" || "d") looks like "if key is a or d," but JavaScript reads it as (key === "a") || ("d"), and a non-empty string counts as true, so the condition is always true. Each side must be a full comparison: key === "a" || key === "d".

Step 7 of 11Compare

&&, || and ! side by side

Aspect&& (and)|| (or)! (not)
True whenBoth sides are trueAt least one side is trueThe value is false
Game examplehasKey && atDoorhealth <= 0 || time <= 0!isPaused
MeansOpen the door only with the key, at the doorGame over if either runs outThe game is running
Common trapUsing it when either case should countkey === "a" || "d" (always true)Forgetting it flips the meaning

Step 8 of 11Note

Step 9 of 11Practice · True or false

The condition hasKey && atDoor is true when the player has the key but is standing far from the door.

Step 10 of 11Practice · Code challenge

Write medal(score) that returns "gold" for 1000 or more, "silver" for 500 to 999, "bronze" for 100 to 499, and "none" for anything lower.

Runs in a sandbox in your browser.
  • medal(1200)
  • medal(1000)
  • medal(500)
  • medal(499)
  • medal(99)

Step 11 of 11Practice · What would you do?

What would you do?

Zane wants the player to move right when either the right arrow or the D key is pressed. He writes if (key === "ArrowRight" || "d"). Now the player slides right constantly, even with no key pressed. What should he change?