JS enginetempwearCondition1let temp = 30;2let wear;3if (temp > 25) {4 wear = "shorts";5} else if (temp > 10) {6 wear = "jacket";7} else {8 wear = "coat";9}10console.log(wear);Consoleshortswear.js:10jacketwear.js:10coatwear.js:1030185truetruefalsefalse"shorts""jacket""coat"
Back: the JavaScript engine, memory (temp and wear) and the condition panelFront: the script wear.js and the console; struck-through lines are skippedMoving: the run marker, values, and the true / false answersAt the back, the JavaScript engine, two memory boxes (temp and wear) and the condition panel. In front, the script wear.js and the console. The violet marker shows the line that runs. At each if or else if, the engine works out the condition and sends its answer, true or false, to the panel; only the first block whose condition is true runs, and the marker jumps over the rest. The script runs three times: temp 30 prints shorts, 18 prints jacket, 5 prints coat.

Making a choice

  1. Normally the engine runs every line, in order, top to bottom. A conditional lets a program choose: some lines run only when a condition is true. This script picks what to wear from the temperature.

Run 1: temp = 30

Run 2: temp = 18

Run 3 and the rules

What happens

// step 1/11 · choose
conditional   code that runs only when a condition is true
condition     a test, such as temp > 25
result        always a boolean: true or false
keywords      if, else if, else
script        wear.js (10 lines)

JavaScript has no elseif keyword. else if is simply else followed by another if statement, which is why you can chain as many as you need. The condition does not have to be a comparison. JavaScript turns any value into true or false: false, 0, -0, 0n, "" (empty text), null, undefined and NaN count as false ("falsy"); every other value counts as true.