The mental model
Until now, your code has run like a train on one straight track: line 1, line 2, line 3, done. Real programs need to choose. Is it raining? Is the password correct? Is the score high enough?
That's what if does. Picture a railway switch in front of the train:
-
The train is your program, carrying a value (like
temperature = 22). -
The switch is the condition in the brackets, like
temperature > 30. It always flips to eithertrueorfalse. -
trueturns the train onto a side track: the code inside{ }runs. -
falselets the train roll straight on to the next switch. -
elseis the last stretch of track. If no switch turned the train, it ends up here.
One rule matters most: the train only ever takes one track. As soon as a switch says true, the train turns off and never looks at the switches below.
Following the train
Each numbered switch matches a numbered comment in the code below.
The code in action
const temperature = 22; // the value our train is carrying
// 1. First switch: is it hot?
if (temperature > 30) {
console.log("Beach day"); // skipped: 22 > 30 is false
}
// 2. Second switch, only checked if switch 1 said false
else if (temperature > 15) {
console.log("Walk in the park"); // runs: 22 > 15 is true
}
// 3. The last stretch of track: no switch turned the train
else {
console.log("Cozy café day"); // never reached this time
}
// Output: "Walk in the park"
-
Tip: Order matters. Put the strictest check first. If you swapped switches 1 and 2, a 35° day would turn off at
> 15and never reach the beach. -
Tip:
else ifandelseare optional. A loneifis a switch with one side track: true runs the code, false skips it. -
Tip: Use
===(three equals) to check if two things are the same, likeanswer === "yes". A single=stores a value in a box; it doesn't compare.
Quick challenge: In your browser console (F12), paste the code above, then change
temperatureto35, then5. Can you predict which station the train reaches before you press Enter?

Top comments (0)