Lesson ยท 12 min
Making choices
Code that decides
A program often has to choose between two paths. The if statement runs a block of code only when a condition is true.
const score = 72;
if (score >= 50) {
console.log('Pass');
} else {
console.log('Try again');
}
The condition goes in parentheses. The code to run goes in braces. The else block runs when the condition is false.
Comparison operators
A comparison gives true or false.
| Operator | Meaning |
|---|---|
=== |
is equal to |
!== |
is not equal to |
> and < |
greater than, less than |
>= and <= |
greater than or equal to, less than or equal to |
Use three equal signs, ===, to compare. One equal sign, =, stores a value in a variable.
Logical operators
You can join conditions.
&&means and. It is true when both sides are true.||means or. It is true when at least one side is true.!means not. It turnstrueintofalse, andfalseintotrue.
More than two paths
Use else if to add more conditions. JavaScript checks them from top to bottom and runs the first block whose condition is true.
Functions in this lesson
The editor has four functions. A function is a named block of code. You can give it values, and it gives a value back with return. You will write your own functions in lesson 8. For now, write your code between the braces of each function. The checker calls each function with many values, so your code must work for all of them.
function double(n) {
return n * 2;
}
Your turn
Do the four tasks in order.
Tasks
4 to do
Task 1, not checked yet. In
describeTemperature, return'Warm'whentemperatureis20or higher. Otherwise return'Cool'. Useifandelse.Task 2, not checked yet. In
canEnter, returntrueonly whenageis12or more andhasTicketistrue. Use the&&operator.Task 3, not checked yet. In
dayType, return'Weekend'whendayis'Sat'or'Sun'. Otherwise return'Weekday'. Use the||operator.Task 4, not checked yet. In
grade, return'A'for90or more,'B'for80or more,'C'for70or more, and'F'for anything lower. Useelse if.
Task 1 of 4
In describeTemperature, return 'Warm' when temperature is 20 or higher. Otherwise return 'Cool'. Use if and else.