Jugami Code Club

Jugami › Code Club › Conditionals

Code Club · Unit 2 · grades 6–8

Conditionals: If, Else, and Decisions

How a program looks at the world, asks a yes-or-no question, and picks what to do next.

In Algorithms and Loops, the robot followed its program blindly. It did the same thing every time, even if a wall was in the way. Real programs have to decide. Is the password right? Did the player touch the lava? Is the room too cold?

In this unit you’ll learn what a condition is, how if and else work, how to compare things and combine questions with and, or and not, and how to fix a condition that’s wrong. Then you’ll write programs for If Bot that work on maps they’ve never seen.

A green robot at a fork in a grid path. A gold gem sits down the left branch. Beside it, a program: if path ahead, forward, else, turn left. ? if path ahead { forward } else { turn left } > path ahead? false → else runs

01What is a condition?

A condition is a question a program can answer with only true or false. Yes or no. Nothing in between.

  • “Is there a wall ahead?” → true or false
  • “Is the score more than 100?” → true or false
  • “Did the player press the jump button?” → true or false

“What color is the sky?” is not a condition, because the answer isn’t true or false. But “Is the sky blue?” is.

A value that can only be true or false is called a Boolean (say it “BOO-lee-un”).2

Did you know? “Boolean” is named after George Boole (1815–1864), an English mathematician born in Lincoln, England. In 1854 he published a book now usually called The Laws of Thought, which treated logic like algebra: statements could be combined and worked out like equations. Today we call that Boolean algebra, and it’s built into every computer.1

02If: do it only when it’s true

An if block checks a condition. If the answer is true, the blocks inside run. If it’s false, they’re skipped and the program carries on below.

  1. if gem here {
  2. pick up
  3. }
  4. forward

Standing on a gem? The robot picks it up, then moves forward. No gem? It skips the pick-up and just moves forward. Either way, forward happens, because it’s outside the if.

Programmers call the true-or-false part the condition and the code inside the curly braces { } the body of the if.

03If / else: pick one of two

Sometimes you want one thing when the answer is true and a different thing when it’s false. That’s what else is for.

  1. if path ahead {
  2. forward
  3. } else {
  4. turn left
  5. }

Exactly one of the two parts runs, never both and never neither. Think of it like a fork in a path: the robot has to take one branch.

Just “if”

Zero or one thing happens. “If it’s raining, take an umbrella.” If it isn’t raining, you do nothing special.

“If / else”

Exactly one of two things happens. “If it’s raining, take an umbrella, else wear sunglasses.”

04Else if: more than two choices

What if there are three or more choices? You can chain them with else if. The computer checks each condition in order, from the top. The first one that’s true wins, and the rest are skipped.3

  1. if score >= 90 {
  2. show "Gold medal"
  3. } else if score >= 70 {
  4. show "Silver medal"
  5. } else if score >= 50 {
  6. show "Bronze medal"
  7. } else {
  8. show "Keep practicing"
  9. }

With a score of 95, the first check is true, so you get Gold. The program never even asks about 70 or 50. That’s good, because 95 is also more than 70, and you don’t want three medals!

Order matters. If you put score >= 50 first, a score of 95 would get Bronze, because 95 >= 50 is true and the chain stops there. When you write a chain, put the strictest check first.

In If Bot there’s no separate “else if” block. You build one by putting an if / else inside the else of another. That’s exactly what an else-if chain is underneath.

05Comparisons (and = vs ==)

Lots of conditions compare two things. Each comparison gives back true or false. These are the ones you’ll see most:4

<
less than: 3 < 5 is true
>
greater than: 3 > 5 is false
<=
less than or equal to: 5 <= 5 is true
>=
greater than or equal to: 4 >= 5 is false
==
is equal to: 5 == 5 is true
!=
is not equal to: 3 != 5 is true

One equals sign or two?

In math class, = means “is equal to.” In many programming languages, including JavaScript and Python, a single = means something different: store this value. lives = 3 puts the number 3 into a box called lives. To ask whether two things are equal, you use two equals signs: lives == 3.45

Stores a value

  1. lives = 3

“Make lives be 3.”

Asks a question

  1. lives == 3

“Is lives 3? True or false?”

Mixing them up is one of the most common beginner bugs. Writing if (lives = 0) by mistake in JavaScript doesn’t check anything; it changes lives to 0.3 (JavaScript also has ===, a stricter “is equal to.” You’ll meet it in Ada’s JavaScript lessons.)

06And, or, not

You can join conditions together, or flip one around. These three words are called logical operators.

and
True only if both parts are true. “You can open the door if you have the key and you’re standing at the door.”
or
True if at least one part is true. “Sleep in if it’s Saturday or Sunday.”
not
Flips true to false and false to true. “If not raining, play outside.”

Here’s a table of every possibility for and and or. Programmers call this a truth table:

Truth table for and / or
ABA and BA or B
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse

Different languages write these differently. Python uses the words and, or, not. JavaScript uses symbols: &&, ||, !.4 The ideas are the same.

07Conditions inside loops

Here’s where it gets powerful. In Algorithms and Loops, a loop repeated the same steps. Put an if inside a loop and the robot checks every time around, so it can do something different on each pass.

  1. repeat until flag {
  2. forward
  3. if gem here {
  4.   pick up
  5. }
  6. }

This 4-block program works on a hallway of any length with gems in any spots. The robot doesn’t need to know the map ahead of time. It just checks as it goes.

repeat until flag is a loop with a condition built in. Before each pass it asks “am I on the flag?” and stops as soon as the answer is true. Real languages have the same idea, often called a while loop (“keep going while this is true”).

Watch out: if the condition never becomes true, an “until” loop never stops. That’s called an infinite loop. If Bot gives up after 400 steps so your browser doesn’t freeze.

08Decisions all around you

Once you start looking, you’ll find conditionals everywhere. Here are three written as programs. (These are simplified to show the idea, not how any real device is built.)

A traffic light

  1. if light == "green" {
  2. go
  3. } else if light == "yellow" {
  4. slow down
  5. } else {
  6. stop
  7. }

A thermostat

  1. repeat forever {
  2. if temperature < 68 {
  3.   heater on
  4. } else {
  5.   heater off
  6. }
  7. }

A game rule

  1. if touchingLava and not hasShield {
  2. lives = lives - 1
  3. }

Notice the thermostat is a condition inside a loop: it checks over and over. And the game rule uses = to store a new value and and not to combine two questions.

09Debugging a wrong condition

When a program makes the wrong choice, the bug is often in the condition itself. Here are the usual suspects:

  • Wrong direction: < where you meant >. The heater turns on when it’s hot!
  • Off by one: > where you meant >=. A score of exactly 90 misses the Gold medal.
  • And vs. or: “key or door” lets you win without the key.
  • A missing or extra “not”: the robot picks up only where there isn’t a gem.
  • = instead of ==: the program stores a value instead of asking a question.
  • Chain in the wrong order: a looser check comes first and catches everything.

How to hunt it down

  1. Pick a real example, like “temperature is 60.”
  2. Work out the condition by hand: is 60 > 68 true or false?
  3. Check which part runs. Is that what you wanted?
  4. Try the edge: test the exact boundary, like 68 itself. Edges are where conditions most often go wrong.

10Play If Bot

How to play: Build one program that gets the robot to the green flag and picks up every gold gem. Most levels have two or three maps, and the same program has to work on all of them, so you can’t just memorize the path. Use if blocks to let the robot look around.

New blocks go where the blinking ▮ insert here marker is. Click any block in your program to move the marker just after it. Use + inside this if, + inside else and + inside this loop to put blocks inside. Choose what a new if checks from the checks list, or press an if block’s change ? button to cycle its condition.

Conditions: path ahead, path to the left, path to the right (no wall that way, from the robot’s point of view), and gem here (a gem is on the robot’s square). Picking up where there’s no gem counts as a mistake.

Scoring: ★ works on every map · ★★ works using an if block · ★★★ uses an if and stays at or under the block target. Your best score for each level is saved only in this browser.

Keyboard: F forward · L turn left · R turn right · K pick up · P repeat · U repeat until flag · I if · E if / else · C change what new ifs check · 2–9 repeat number · Backspace delete the block before the marker · G run · S step · T try again · M next map. Tab moves between buttons; press Enter on a “+ inside” button to move the marker there.

The six levels

  1. Look before you grab. Walk a hallway and pick up only where there’s a gem. 1 map. Target: 4 blocks.
  2. Two hallways. Same hallway, gems in different spots on each map. 2 maps. Target: 4 blocks.
  3. How far? Hallways of different lengths. 2 maps. Target: 4 blocks (hint: repeat until flag).
  4. Left or right? The path turns left on one map and right on the other. 2 maps. Target: 6 blocks.
  5. Gem trail. Three winding paths with gems. 3 maps. Target: 8 blocks.
  6. Maze runner. Two mazes with dead ends. 2 maps. Target: 7 blocks (hint: the right-hand rule).

11Fix the condition

Each program below has exactly one wrong line, and it’s always a condition. Read the goal, try a real example in your head, and find the line that’s wrong, then click it.

1: The backwards heater

Goal: turn the heater on when the room is colder than 68 degrees.

Show the answer

The bug is temperature > 68. Try 60 degrees: 60 > 68 is false, so the heater turns off in a cold room. It should be temperature < 68.

2: The stuck traffic light

Goal: go on green, slow down on yellow, stop on red.

Show the answer

The bug is the second check, light == "green". Green was already caught by the first line, so “slow down” can never run, and a yellow light falls through to “stop.” It should be light == "yellow".

3: The keyless door

Goal: the player wins only when they have the key and are standing at the door.

Show the answer

The bug is hasKey or atDoor. With “or,” walking up to the door without the key is enough to win. It should be hasKey and atDoor.

4: The upside-down gem grabber

Goal: walk to the flag, picking up a gem on every square that has one.

Show the answer

The bug is if not gem here. The extra “not” makes the robot try to pick up only on squares without a gem. It should be if gem here.

12Self-guided quiz

1. A condition in a program is…

2. The word “Boolean” is named after…

3. temperature is 72. What does if temperature < 65 { show "jacket" } else { show "T-shirt" } show?

4. score is 85. The chain is: if score >= 90 show “A”, else if score >= 80 show “B”, else if score >= 70 show “C”, else show “Try again.” What shows?

5. In JavaScript and Python, what does == do?

6. Rule: “Go to recess if your work is done and it is not raining.” Your work is done, but it is raining. What happens?

7. if day == "Saturday" or day == "Sunday" { sleep in }. Today is Sunday. What happens?

8. In If Bot’s “Two hallways” level, why does the program need “if gem here”?

9. The robot is on a square with no gem. What does if not gem here { forward } do?

13Talk About It

There are no single right answers here. Talk with a friend, your class, or a grown-up.

  • Write the rules of a game you know (tag, a board game, a video game) as if/else statements. Which rule needed an “and” or an “or”?
  • In If Bot, your program had to work on maps it had never seen. Why is that more useful than a program that only works on one map?
  • The right-hand rule gets through some mazes but not every maze. Can you draw a maze where it would go around in circles forever?
  • Think of a time a machine made the wrong decision for you, like an automatic door or a phone autocorrect. What condition might have been wrong?
  • Some decisions are hard to turn into true or false, like “is this song good?” Should computers make decisions like that? Why or why not?

14Sources and credits

  1. J. J. O’Connor and E. F. Robertson, “George Boole,” MacTutor History of Mathematics, University of St Andrews: born 1815 in Lincoln, died 1864; An Investigation of the Laws of Thought (1854); Boolean algebra. mathshistory.st-andrews.ac.uk: Boole
  2. MDN Web Docs, “Boolean” (glossary): a Boolean is a value that is either true or false, named after the English mathematician George Boole. developer.mozilla.org: Boolean
  3. MDN Web Docs, “if...else” (JavaScript reference): else-if chains, and the warning against using an assignment like x = y as a condition. developer.mozilla.org: if...else
  4. MDN Web Docs, “Expressions and operators” (JavaScript guide): assignment, comparison operators, and the logical operators &&, || and !. developer.mozilla.org: Expressions and operators
  5. Python documentation, “Expressions: Comparisons” and “Boolean operations”: ==, !=, < and friends, and and, or, not. docs.python.org: Comparisons

Credits. Written for jugami.com by Grace, the Jugami Code Club teacher. The robot, game boards, favicon and share image are original art made in code (hand-written SVG) for this page. The traffic light, thermostat and game examples are simplified illustrations, not descriptions of real devices. If Bot runs only in your browser. It saves your best stars in this browser’s local storage and sends nothing anywhere.