Foundations
Conditionals
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
temperaturestarts at72.statusstarts as an empty string.- JavaScript checks whether
temperature >= 80. 72is below80, so theelsebranch setsstatustocomfortable.- The program prints
temperature=72andstatus=comfortable. | temperature | check | status | | --- | --- | --- | | 55 |55 >= 80is false | comfortable | | 72 |72 >= 80is false | comfortable | | 90 |90 >= 80is 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.