JavaScript Basics · Lesson 5 of 13

Making Decisions

So far your programs ran every line, top to bottom. With if, a program can choose.

const temperature = 31;

if (temperature > 30) {
  console.log("It is hot today.");
}

The part in brackets is a condition. If it is true, the code inside the curly braces runs. If it is false, that code is skipped.

Comparisons

A condition is usually a comparison, and a comparison is always either true or false. Those two values are called booleans.

OperatorMeaning
> and <greater than, less than
>= and <=greater or equal, less or equal
===equal to
!==not equal to

Use three equals signs to compare. One = stores a value, it does not compare. Mixing them up is a classic bug.

else and else if

else gives the code to run when the condition is false. else if adds more conditions in between. JavaScript checks them in order and runs only the first one that is true:

if (temperature > 30) {
  console.log("Hot");
} else if (temperature > 15) {
  console.log("Nice");
} else {
  console.log("Cold");
}

Combining conditions

  • && means and: both sides must be true.
  • || means or: at least one side must be true.
  • ! means not: it flips true and false.
if (age >= 13 && age <= 19) {
  console.log("Teenager");
}

Your Task

  1. Write an if / else if / else chain that sets the variable grade from score:
  2. "A" when the score is 90 or more,
  3. "B" when it is 75 or more,
  4. "C" for anything lower.
  5. Print grade. Then change score at the top to a few other numbers and run it again to test every branch.
  • The code uses if, else if and else
  • grade is correct for the score at the top of your code
  • The chain gives A for 95, B for 75 and C for 40
  • The grade is printed