JavaScript

Lesson 5 of 11

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 turns true into false, and false into true.

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

  1. Task 1, not checked yet. In describeTemperature, return 'Warm' when temperature is 20 or higher. Otherwise return 'Cool'. Use if and else.

  2. Task 2, not checked yet. In canEnter, return true only when age is 12 or more and hasTicket is true. Use the && operator.

  3. Task 3, not checked yet. In dayType, return 'Weekend' when day is 'Sat' or 'Sun'. Otherwise return 'Weekday'. Use the || operator.

  4. Task 4, not checked yet. In grade, return 'A' for 90 or more, 'B' for 80 or more, 'C' for 70 or more, and 'F' for anything lower. Use else if.

Task 1 of 4

In describeTemperature, return 'Warm' when temperature is 20 or higher. Otherwise return 'Cool'. Use if and else.

All tasks

main.js

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.