← All lessons/Conditionals· Lesson 11 of 32

if / else

Use else and else-if chains to choose between two or more options.

About 7 min

Plan B with else

An if runs code when its condition is true. Add an else block and you also handle the case when it's false — exactly one of the two blocks runs:

if (condition) {
  // runs when true
} else {
  // runs when false
}
One path or the other — never both.

Choosing between many options

Chain else if to test several conditions in order. p5 checks them top to bottom and runs the first one that's true:

A score of 85 lands in the middle branch, painting gold.

TIP

Order matters: put the most specific or highest conditions first, since the first true branch wins and the rest are skipped.

Your turn

A variable hour is set to 20. Write an if / else: if hour < 18, call background(135, 206, 235) for a daytime sky; otherwise (else), call background(20, 20, 60) for a night sky. Since hour is 20, the night branch should run.

Hints