JavaScript Conditional Statements: Build a Quiz That Explains Your Answer

JavaScript conditional statements let a webpage respond differently to different situations. A quiz is a useful way to practise: an unanswered question needs a prompt, a correct answer deserves confirmation, and an incorrect answer needs an explanation.

In this tutorial, you will build a one-question quiz with if, else if and else. You will connect variables, HTML IDs and CSS classes to produce helpful feedback. If you have completed Lesson 14: Read input and make a choice, this project takes that simple condition further.

What you will build

The question is: Which language styles a webpage? Readers choose HTML, CSS or JavaScript, then select Check answer. Each choice produces a useful explanation. Leaving the question unanswered produces a reminder.

The quiz runs in your browser. It does not submit answers to a server or save a score. Its purpose is to make the decision process easy to see and change.

Try the complete example

Copy the entire example below into the Playcode123 Code Sandbox, replacing its starter code, and choose Run Code. Alternatively, save it as quiz.html in a plain-text editor and open that file in your browser. The quiz appears in the Sandbox preview; the code displayed in this article is for copying.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>A quiz that explains your answer</title>
  <style>
    body { font-family: system-ui, sans-serif; line-height: 1.6;
      margin: 0; padding: 20px; color: #172b3a; background: #f4f7fb; }
    main { max-width: 640px; margin: auto; }
    select, button { font: inherit; max-width: 100%; padding: 10px; }
    label { display: block; margin-bottom: 8px; }
    button { margin-top: 12px; cursor: pointer; }
    :focus-visible { outline: 3px solid #145da0; outline-offset: 3px; }
    .feedback { padding: 16px; border: 2px solid #526171; border-radius: 8px; }
    .correct { color: #14532d; background: #ecfdf5; border-color: #166534; }
    .retry { color: #78350f; background: #fffbeb; border-color: #92400e; }
  </style>
</head>
<body>
<main>
  <h1>Which language styles a webpage?</h1>
  <p>Choose an answer to discover why it fits or does not fit.</p>
  <form id="quiz-form">
    <label for="answer">Your answer</label>
    <select id="answer" name="answer">
      <option value="">Choose an answer</option>
      <option value="html">HTML</option>
      <option value="css">CSS</option>
      <option value="javascript">JavaScript</option>
    </select>
    <br>
    <button type="submit">Check answer</button>
  </form>
  <p id="feedback" class="feedback" role="status">Your explanation will appear here.</p>
</main>
<script>
  const form = document.getElementById("quiz-form");
  const answerInput = document.getElementById("answer");
  const feedback = document.getElementById("feedback");

  form.addEventListener("submit", function (event) {
    event.preventDefault();
    const answer = answerInput.value;
    let message = "";
    let isCorrect = false;

    if (answer === "") {
      message = "Choose an answer first, then check it.";
    } else if (answer === "css") {
      message = "Correct! CSS defines colours, fonts, spacing and layout.";
      isCorrect = true;
    } else if (answer === "html") {
      message = "Try again. HTML gives content structure. CSS controls its appearance.";
    } else {
      message = "Try again. JavaScript adds behaviour and can change styles, but CSS defines the styling rules.";
    }

    feedback.textContent = message;
    feedback.classList.toggle("correct", isCorrect);
    feedback.classList.toggle("retry", !isCorrect);
  });

  answerInput.addEventListener("change", function () {
    feedback.textContent = "Selection changed. Choose Check answer for feedback.";
    feedback.classList.remove("correct", "retry");
  });
</script>
</body>
</html>

How the conditional statements choose a response

Read the decision chain from top to bottom. JavaScript runs the first matching branch and skips the remaining branches in that chain. The final else handles a choice that did not match an earlier condition.

  1. if (answer === ""): the placeholder option has an empty value, so the quiz asks for an answer.
  2. else if (answer === "css"): CSS is the correct choice. The code sets a success message and changes isCorrect to true.
  3. else if (answer === "html"): the quiz explains that HTML gives content structure.
  4. else: with the options supplied, the remaining choice is JavaScript. The explanation acknowledges that JavaScript can change styles while CSS defines the styling rules.

The last branch is a fallback, not a hidden test for JavaScript. If you add another option, that option also reaches the fallback unless you add a matching condition. We will use that fact in the exercise.

Keep the empty-answer check first: missing input deserves its own response. For conditions that overlap, order matters even more. For example, in a score quiz, a score of 90 satisfies both score >= 50 and score >= 80. Checking the higher threshold first lets you give the more specific result.

Variables: what stays fixed and what changes?

The first three const variables hold references to the form, dropdown and feedback paragraph. Inside the submit handler, answer stores the dropdown’s current value. It is read again every time you check an answer.

message and isCorrect use let because the branches assign new values to them. They start fresh on each submission, so an earlier correct result does not carry over into a later attempt. For a refresher, see the blog’s JavaScript variables tutorial.

=== compares values without converting their types. These option values are strings, so the code compares them with quoted strings such as "css". For example, "3" === 3 is false: one value is text and the other is a number.

Connect HTML IDs, CSS classes and feedback

An id identifies one element in this document. getElementById("feedback") finds the paragraph with id="feedback". The label’s for="answer" also matches the dropdown’s ID, giving the control a visible label.

A CSS class can be reused on multiple elements. The paragraph keeps its base feedback class for padding and borders. JavaScript adds or removes the correct and retry classes to change its appearance.

In classList.toggle("correct", isCorrect), the second argument controls whether the class is present: true adds it, false removes it. The ! in !isCorrect reverses that Boolean for the retry class. These are CSS classes, not JavaScript class declarations.

The words “Correct!” and “Try again” communicate the result alongside colour. The paragraph uses role="status" so assistive technology can announce updates. textContent inserts the explanation as text.

Why the page stays open and old feedback disappears

The listener handles the form’s submit event. event.preventDefault() stops the normal form navigation so the quiz can display its feedback on the same page.

The separate change listener resets the message and removes both result classes when a new option is selected. Otherwise a green “Correct!” message could remain visible beside a newly selected wrong answer. The reader then checks the new choice explicitly.

Test every route through the quiz

  • No answer: leave “Choose an answer” selected and check it. You should see the reminder.
  • CSS: check this choice. You should see “Correct!” and green feedback.
  • HTML: switch to HTML. Old feedback should clear; checking should explain HTML’s role.
  • JavaScript: check this choice and read its different explanation.
  • Try again: return to CSS, then back to the placeholder. Each result should reflect the current selection.
  • Keyboard: use Tab to reach the dropdown, arrow keys to choose an option, and Tab then Enter to activate the button. Keep an eye on the visible focus outline.

Common mistakes and how to fix them

  • Using = in a condition: this assigns a value. Use === when you intend a strict comparison.
  • Comparing the visible label: the option displays “CSS”, but its value is "css". Match the value’s spelling and case.
  • Writing several separate if statements: more than one can run. Use an else if chain when exactly one response should be chosen.
  • Renaming an ID in only one place: update its HTML, label and JavaScript references together.
  • Adding an option without updating the logic: the fallback message may describe the wrong choice.

Your challenge: add a fourth answer

Add Python as another option with value="python". Before changing the script, predict the result: it will receive the current JavaScript explanation because it reaches else.

Now make the JavaScript option an explicit else if (answer === "javascript") branch. Add another branch for Python that explains it is a general-purpose language, not the language used to define this page’s CSS styling. Finish with a generic else message such as “That answer is not recognised. Choose one of the listed options.”

Test all four options and the placeholder again. You have now extended a decision chain while keeping each explanation accurate. As a further exercise, change the question and update the options, comparisons and feedback together.

Continue learning

Use the JavaScript functions tutorial to explore moving your answer-checking logic into a named function. Keep this version focused on if, else if and else; switch and the ternary operator are useful topics for a separate comparison.

Technical references: MDN: if…else, MDN: strict equality.