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.
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.
- if gem here {
- pick up
- }
- 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.
- if path ahead {
- forward
- } else {
- turn left
- }
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
- if score >= 90 {
- show "Gold medal"
- } else if score >= 70 {
- show "Silver medal"
- } else if score >= 50 {
- show "Bronze medal"
- } else {
- show "Keep practicing"
- }
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 < 5is true >- greater than:
3 > 5is false <=- less than or equal to:
5 <= 5is true >=- greater than or equal to:
4 >= 5is false ==- is equal to:
5 == 5is true !=- is not equal to:
3 != 5is 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
- lives = 3
“Make lives be 3.”
Asks a question
- 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:
| A | B | A and B | A or B |
|---|---|---|---|
| true | true | true | true |
| true | false | false | true |
| false | true | false | true |
| false | false | false | false |
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.
- repeat until flag {
- forward
- if gem here {
- pick up
- }
- }
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
- if light == "green" {
- go
- } else if light == "yellow" {
- slow down
- } else {
- stop
- }
A thermostat
- repeat forever {
- if temperature < 68 {
- heater on
- } else {
- heater off
- }
- }
A game rule
- if touchingLava and not hasShield {
- lives = lives - 1
- }
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
- Pick a real example, like “temperature is 60.”
- Work out the condition by hand: is
60 > 68true or false? - Check which part runs. Is that what you wanted?
- Try the edge: test the exact boundary, like 68 itself. Edges are where conditions most often go wrong.
If Bot, the robot game for this unit, is online at jugami.com/code-club/conditionals/
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.
Blocks
Your program
The six levels
- Look before you grab. Walk a hallway and pick up only where there’s a gem. 1 map. Target: 4 blocks.
- Two hallways. Same hallway, gems in different spots on each map. 2 maps. Target: 4 blocks.
- How far? Hallways of different lengths. 2 maps. Target: 4 blocks (hint: repeat until flag).
- Left or right? The path turns left on one map and right on the other. 2 maps. Target: 6 blocks.
- Gem trail. Three winding paths with gems. 3 maps. Target: 8 blocks.
- 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
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
- 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
- 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
- MDN Web Docs, “if...else” (JavaScript reference): else-if chains, and the warning against using an assignment like
x = yas a condition. developer.mozilla.org: if...else - MDN Web Docs, “Expressions and operators” (JavaScript guide): assignment, comparison operators, and the logical operators
&&,||and!. developer.mozilla.org: Expressions and operators - Python documentation, “Expressions: Comparisons” and “Boolean operations”:
==,!=,<and friends, andand,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.