Games are full of decisions: did the player win? is health zero? did we hit something? An if statement runs a block of code only when something is true — that’s how your game reacts.
1. if
Put a true/false test in the parentheses. The block runs only if the test is true:
let score = 7;
function draw() {
cls(1);
if (score > 5) {
print('You win!', 8, 8, 11);
}
}Change score to 3 and save — the message disappears, because 3 > 5 is false and the block is skipped.
2. else
else gives you the other path — it runs when the if test is false, so exactly one of the two blocks always runs:
let score = 3;
function draw() {
cls(1);
if (score > 5) {
print('You win!', 8, 8, 11);
} else {
print('Try again', 8, 8, 8);
}
}3. else if
For more than two paths, chain else if. JavaScript checks each test in order and runs the first one that’s true:
let health = 20;
function draw() {
cls(1);
if (health > 60) {
print('Healthy', 8, 8, 11);
} else if (health > 25) {
print('Careful', 8, 8, 10);
} else {
print('Danger!', 8, 8, 8);
}
}The tests inside the parentheses are the comparisons from Booleans (>, <, ===, …), and you can join them with && and || for trickier conditions.
Use === to compare, not =. A single = stores a value; === checks whether two values are equal. Writing if (health = 0) sets health to 0 instead of testing it — a classic first bug.
What you learned
if (test) { … }runs its block only whentestistrue.elseruns when theifwas false; exactly one block runs.else ifchains more paths — the first true one wins.- The test is a boolean (a comparison); compare with
===, not=.