An if statement lets JavaScript choose between branches.

Conditionals

conditionals.js
const temperature = 72;
let status = "";

if (temperature >= 80) {
  status = "warm";
} else {
  status = "comfortable";
}

console.log("temperature=" + temperature);
console.log("status=" + status);

Follow the Branch

  1. temperature starts at 72.
  2. status starts as an empty string.
  3. JavaScript checks whether temperature >= 80.
  4. 72 is below 80, so the else branch sets status to comfortable.
  5. The program prints temperature=72 and status=comfortable. | temperature | check | status | | --- | --- | --- | | 55 | 55 >= 80 is false | comfortable | | 72 | 72 >= 80 is false | comfortable | | 90 | 90 >= 80 is true | warm |
if statement An `if` statement runs one block when its condition is true and can use `else` for the other case.

Exercise: conditionals.js

Reproduce status=comfortable for temperature 72, then try 55 and 90 and predict the branch result.