Making decisions
Programs become useful when they react. if runs code only when a condition is true:
const temperature = 31;
if (temperature > 30) {
console.log("It's hot. Drink water!");
} else {
console.log("Nice weather.");
}
The condition goes in brackets. The code to run goes in curly braces { }. else is what happens otherwise.
Ways to compare:
| Code | Means |
|---|---|
a === b |
a equals b |
a !== b |
a does not equal b |
a > b, a < b |
more than, less than |
a >= b, a <= b |
at least, at most |
Note the three equals signs in ===. A single = stores a value; it does not compare.
Asking for input
prompt("Question?") asks the person running the program for an answer. Here, answers come from the input box above the Run button, one per line. prompt always gives back text, so turn it into a number with Number(...) before comparing:
const age = Number(prompt("How old are you?"));
Your task
Ask for the person's age. If they are 18 or older, print You can vote. Otherwise print Too young to vote.
Try different ages in the input box and press Run ▶ each time.