Codiqo

Learn JavaScript · lesson 16 of 60 · about 9 minutes

Project: Quiz Results

Sam's page gets a quiz: check the score the visitor typed, turn it into a grade with else if, and say pass or try again with a ternary.

What you'll learn

  • Map number ranges to grades
  • Validate input
  • Format a report

Sam's quiz

Sam's page now has a short quiz, and visitors type their score into a box. The page should turn the score into a grade and say whether they passed, and it mustn't fall over when someone types 104 or banana.

The plan

For each score:

1. Reject anything outside 0 to 100
2. Work out the grade with else if, checking the highest band first
3. Use a ternary to say pass or fail

Catching bad input

The score arrives as text, so convert it with Number(). Typing banana gives NaN, and NaN isn't equal to anything, not even itself, so score === NaN is always false. Check with Number.isNaN(score) instead.

The calculator

const score = 73;
let grade;

if (score < 0 || score > 100) {
  grade = "invalid";
} else if (score >= 90) {
  grade = "A";
} else if (score >= 75) {
  grade = "B";
} else if (score >= 60) {
  grade = "C";
} else {
  grade = "F";
}

const result = grade === "F" ? "fail" : "pass";
console.log(`Score ${score}: grade ${grade} (${result})`);

Output

Score 73: grade C (pass)

The quiz on Sam's page

const scoreText = "73";
const score = Number(scoreText);
const quiz = document.querySelector("#quiz");
if (Number.isNaN(score) || score < 0 || score > 100) {
  quiz.textContent = "Please enter a score from 0 to 100";
} else {
  let grade;
  if (score >= 90) {
    grade = "A";
  } else if (score >= 75) {
    grade = "B";
  } else if (score >= 60) {
    grade = "C";
  } else {
    grade = "F";
  }
  const result = grade === "F" ? "try again" : "passed";
  quiz.textContent = `Quiz: ${score}, grade ${grade} (${result})`;
}

Tip

Test the edges: exactly 90, 75 and 60, then 0, 100, 101 and a word.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.