Back to Variable Challenge
Code Studio · Level 3

Real If / Then

Give your program a brain. With if / then, your code checks a condition and chooses what happens next — the secret behind every locked door in every game.

15-20 min Ages 9-12 Real Code JavaScript

What is if / then?

An if statement is how a program makes a choice. Think of it like a guard at a treasure door: the guard asks one question — "Do you have the key?" If the answer is true, the door opens and the code inside runs. If it's false, the program skips that code completely and moves on, like the door never existed.

hasKey? the condition true → run the code inside { } false → skip it completely
  1. 1

    The three parts: if (condition) { action }

    if tells JavaScript a choice is coming. The parentheses ( ) hold the question the program checks. The curly braces { } hold the then part — the code that runs only when the answer is true.

  2. 2

    true and false are real values

    let hasKey = true; stores a boolean — a special yes/no value. Booleans never get quotes: true is an answer, but "true" is just a word. When the program reaches if (hasKey), it opens the box and checks the answer inside.

  3. 3

    Watch the program choose

    Run the example and the robot says "Open the treasure door." Now change true to false and run again — the robot says nothing, because the door stayed shut. Same code, different choice. That's the whole power of if / then.

Code Editor

Run a condition.

Example code
let hasKey = true;

if (hasKey) {
  say("Open the treasure door.");
}
Output

Program result

Robot ready to speak your strings

Type real JavaScript, then run it.