ILILCode

Conditionals: if, else and switch

Pick a path through your code with if, else if, else — and know when a switch reads better.

Lesson 4 of 23 in JavaScript8 min1 exercise

An if runs a block when its condition is truthy. else if is checked only when everything above failed, and else catches the rest. Order the checks from most specific to most general.

A chain of checks
const score = 82;

if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else if (score >= 70) {
  console.log("C");
} else {
  console.log("Keep going");
}

Braces are optional for a single statement. Use them anyway — the cost of two characters is lower than the cost of a confusing bug.

Truthy and falsy

These six values are falsy: false, 0, -0, "", null, undefined, NaN. Everything else is truthy — including "0", [] and {}.

switch compares with ===
const day = "sat";

switch (day) {
  case "sat":
  case "sun":
    console.log("Weekend");
    break;
  default:
    console.log("Weekday");
}

Try it

Change the score

main.js
console · output appears here

Exercises

Checked in your browser · hints and solutions included

01

Exercise

Turn a score into a grade

Write grade(score) that returns:

  • "A" for 90 and above
  • "B" for 80–89
  • "C" for 70–79
  • "D" for 60–69
  • "F" below 60

Check the highest boundary first.

exercise.js
console · run your code or check the answer