← All lessons/Conditionals· Lesson 10 of 32

The if statement

Use if and comparison operators to run some code only when a condition is true.

About 6 min

Making a decision

An if statement runs a block of code only when a condition is true. You write if, a condition in parentheses, and the code to run in curly braces:

if (condition) {
  // runs only when condition is true
}
The shape of an if statement.

Comparison operators

Conditions are usually comparisons that come out true or false. The operators are:

  • a < b — less than
  • a > b — greater than
  • a <= b — less than or equal to
  • a >= b — greater than or equal to
  • a === b — equal to (three equals signs!)
  • a !== b — not equal to

Use ===, not =

A single = assigns a value; three of them === compares. To test if score is 10, write if (score === 10).

The circle is only drawn because 7 is greater than 5.

Try changing 7 to 3 and press Run — now the condition is false, so the circle never appears.

Your turn

A variable temperature is set to 90. Add an if statement that checks whether temperature > 80; when it is, call background(255, 100, 0) to paint the canvas hot orange.

Hints