DEV Community

Cover image for Track Switches: How JavaScript Makes Decisions
Ayekple Clemence
Ayekple Clemence

Posted on

Track Switches: How JavaScript Makes Decisions

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 either true or false.
  • true turns the train onto a side track: the code inside { } runs.
  • false lets the train roll straight on to the next switch.
  • else is 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

Flowchart: temperature = 22 fails switch 1 (temperature > 30), passes switch 2 (temperature > 15) and arrives at

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"
Enter fullscreen mode Exit fullscreen mode
  • Tip: Order matters. Put the strictest check first. If you swapped switches 1 and 2, a 35° day would turn off at > 15 and never reach the beach.
  • Tip: else if and else are optional. A lone if is 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, like answer === "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 temperature to 35, then 5. Can you predict which station the train reaches before you press Enter?

Top comments (0)