Skip to content
jshacks.dev
Browser

Build a Quiz App in Vanilla JavaScript

Build a quiz app in vanilla JavaScript with a question data model, one render function, scoring, answer feedback, a results screen and accessible radio inputs.

8 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the JavaScript, Google Chrome, Swagger, GraphQL and NGINX logos.

A quiz is a state machine with a friendly face: show a question, accept one answer, give feedback, move to the next question and finally show a score. Building one in vanilla JavaScript teaches the pattern that most interfaces share, which is a small piece of state, a function that draws the screen from that state and handlers that change the state and draw again. This post builds a quiz app in vanilla JavaScript with a question data model, scoring that is separate from the page, accessible radio inputs, immediate feedback, a progress indicator, a results screen with a restart button and the ability to shuffle questions and answers without losing track of which is correct. Along the way you will see where bugs hide in quizzes, mostly in how correct answers are stored. The form elements are documented on MDN.

The questions as data

Keep the questions in an array of objects, with the correct answer stored as an index into the choices.

questions.jsJavaScript
export const QUESTIONS = [
  {
    id: "typeof-null",
    text: "What does typeof null return?",
    choices: ["null", "object", "undefined", "number"],
    answer: 1,
    explanation: "A long-standing quirk: typeof null is 'object'.",
  },
  {
    id: "array-length",
    text: "What is [1, 2, 3].length?",
    choices: ["2", "3", "4", "undefined"],
    answer: 1,
    explanation: "length is the number of elements.",
  },
  {
    id: "strict-equal",
    text: "What does 1 === '1' evaluate to?",
    choices: ["true", "false", "NaN", "It throws"],
    answer: 1,
    explanation: "=== compares without type coercion, so the types differ.",
  },
];

console.log(QUESTIONS.length, QUESTIONS[0].choices[QUESTIONS[0].answer]);
Text
3 object

Storing the answer as an index is simple, but it becomes a bug the moment you shuffle the choices: the index no longer points at the right text. The fix, shown later, is to shuffle objects that carry their own correct flag, or to remember the correct text.

The quiz logic

Keep the logic out of the DOM. A quiz object tracks the current position, the answers and the score.

quiz.jsJavaScript
export function createQuiz(questions) {
  const answers = new Array(questions.length).fill(null);
  let index = 0;

  return {
    get index() { return index; },
    get total() { return questions.length; },
    get finished() { return index >= questions.length; },
    get question() { return questions[index]; },
    get score() {
      return answers.filter((choice, i) => choice === questions[i].answer).length;
    },
    answer(choice) {
      if (answers[index] !== null) return false;
      answers[index] = choice;
      return choice === questions[index].answer;
    },
    answered() { return answers[index] !== null; },
    chosen() { return answers[index]; },
    next() { if (index < questions.length) index += 1; },
    restart() { answers.fill(null); index = 0; },
  };
}

const quiz = createQuiz([
  { text: "q1", choices: ["a", "b"], answer: 0 },
  { text: "q2", choices: ["a", "b"], answer: 1 },
]);
console.log(quiz.answer(0), quiz.answer(1));
quiz.next();
console.log(quiz.answer(0));
console.log(quiz.score, quiz.total);
Text
true false
false
1 2

The first answer(0) is correct and returns true. A second call for the same question is ignored and returns false, so the score cannot be changed by clicking again. On the next question, choosing the wrong choice gives false, so the final score is 1 of 2. Because score is computed from the recorded answers each time, it can never get out of step with them.

The page

The structure has a progress line, a form for the question and a feedback area. A <fieldset> with a <legend> is the correct markup for a group of radio buttons, because it tells assistive technology what question the choices belong to.

index.htmlHTML
<main id="app">
  <p id="progress"></p>
  <form id="question" hidden>
    <fieldset>
      <legend id="text"></legend>
      <div id="choices"></div>
    </fieldset>
    <button type="submit" id="check">Check answer</button>
    <button type="button" id="next" hidden>Next</button>
  </form>
  <p id="feedback" role="status" aria-live="polite"></p>
  <section id="results" hidden>
    <h2>Results</h2>
    <p id="score"></p>
    <button type="button" id="restart">Try again</button>
  </section>
</main>
<script type="module" src="app.js"></script>
Text
(a progress line, a question form, a feedback line and a hidden results section)

Render the question

One function draws the current question. It builds radio inputs inside labels, which makes the whole label clickable and gives each input an accessible name.

render.jsJavaScript
const form = document.querySelector("#question");
const textEl = document.querySelector("#text");
const choicesEl = document.querySelector("#choices");
const progress = document.querySelector("#progress");

export function renderQuestion(quiz) {
  const { question, index, total } = quiz;
  progress.textContent = `Question ${index + 1} of ${total}`;
  textEl.textContent = question.text;
  choicesEl.replaceChildren();

  question.choices.forEach((choice, i) => {
    const label = document.createElement("label");
    const input = document.createElement("input");
    input.type = "radio";
    input.name = "choice";
    input.value = String(i);
    label.append(input, ` ${choice}`);
    choicesEl.append(label);
  });

  form.hidden = false;
  form.querySelector("#check").hidden = false;
  form.querySelector("#next").hidden = true;
  document.querySelector("#feedback").textContent = "";
  choicesEl.querySelector("input").focus();
}

export function showResult(quiz, wasRight) {
  const { question } = quiz;
  choicesEl.querySelectorAll("label").forEach((label, i) => {
    label.classList.toggle("correct", i === question.answer);
    label.classList.toggle("wrong", i === quiz.chosen() && i !== question.answer);
    label.querySelector("input").disabled = true;
  });
  document.querySelector("#feedback").textContent =
    `${wasRight ? "Correct." : "Not quite."} ${question.explanation ?? ""}`;
  form.querySelector("#check").hidden = true;
  form.querySelector("#next").hidden = false;
  form.querySelector("#next").focus();
}
Text
(radio buttons for each choice; after checking, the right answer is marked and an explanation is shown)

The text goes in with append and textContent, never innerHTML, so a choice like <b> displays as text. Moving focus to the first input, then to the Next button after checking, keeps keyboard users in the flow. The color classes should never be the only signal, so the feedback sentence also says "Correct" or "Not quite".

Wire the events

The form's submit handler checks the answer; the Next button moves on.

app.jsJavaScript
import { QUESTIONS } from "./questions.js";
import { createQuiz } from "./quiz.js";
import { renderQuestion, showResult } from "./render.js";

const quiz = createQuiz(QUESTIONS);
const form = document.querySelector("#question");
const results = document.querySelector("#results");

function showQuestion() {
  results.hidden = true;
  renderQuestion(quiz);
}

function showScore() {
  form.hidden = true;
  document.querySelector("#progress").textContent = "Finished";
  document.querySelector("#score").textContent = `You scored ${quiz.score} out of ${quiz.total}.`;
  results.hidden = false;
  results.querySelector("button").focus();
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const picked = new FormData(form).get("choice");
  if (picked === null) {
    document.querySelector("#feedback").textContent = "Choose an answer first.";
    return;
  }
  const right = quiz.answer(Number(picked));
  showResult(quiz, right);
});

document.querySelector("#next").addEventListener("click", () => {
  quiz.next();
  if (quiz.finished) showScore();
  else showQuestion();
});

document.querySelector("#restart").addEventListener("click", () => {
  quiz.restart();
  showQuestion();
});

showQuestion();
console.log(document.querySelector("#progress").textContent);
Text
Question 1 of 3

Using a form and its submit event means pressing Enter checks the answer, and FormData reads the selected radio without any manual bookkeeping. If nothing is selected, get("choice") returns null, and the handler asks the user to choose.

Shuffle without breaking the answers

Shuffling stops people memorizing the position. Do it by shuffling objects that know which one is correct, not by shuffling plain strings next to an index.

shuffle.jsJavaScript
export function shuffle(items, random = Math.random) {
  const copy = [...items];
  for (let i = copy.length - 1; i > 0; i--) {
    const j = Math.floor(random() * (i + 1));
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}

export function prepare(question, random) {
  const choices = shuffle(
    question.choices.map((text, i) => ({ text, correct: i === question.answer })),
    random
  );
  return {
    ...question,
    choices: choices.map((c) => c.text),
    answer: choices.findIndex((c) => c.correct),
  };
}

const prepared = prepare({ text: "q", choices: ["a", "b", "c"], answer: 1 }, () => 0);
console.log(prepared.choices, prepared.answer);
Text
[ 'a', 'c', 'b' ] 2

With a random function that always returns 0, the Fisher-Yates shuffle is fully deterministic, so the result is reproducible: the correct choice "b" moves to the end, and the new answer index is 2. Passing the random function as a parameter makes the shuffle testable. Call prepare on every question once when the quiz starts.

Practical notes

Do not ship answers that a visitor can read in the page if the quiz is a real assessment: the data is in the script, so anyone can open the developer tools. For a learning quiz that is fine. Support keyboard use fully, which radio groups give you for free with the arrow keys. Add a timer only when it serves a purpose, and then provide a way to extend it for people who need more time. Store the best score in localStorage if you want a high score, guarded with try and catch. Finally, keep questions in a JSON file you can edit without touching code, and validate its shape at load time so a typo does not become a runtime crash halfway through a quiz.

Extending the quiz

The structure leaves room to grow. For a timed quiz, store a start time and compute the remaining seconds exactly as the pomodoro timer does, from timestamps instead of ticks. For multiple correct answers, use checkboxes instead of radio inputs and store the answer as a sorted array, comparing it to the chosen array. For questions with code, put the snippet in a <pre><code> element created with textContent, so the characters are shown as typed.

Scoring can become more interesting than a simple count. Weighted questions give each item a points field, and the score sums the points of correct answers. A review screen can list every question with the chosen and the correct answer, which is the part learners value most, since the point of a quiz is to find out what to study next. Store each attempt in localStorage with a date, and you can show progress over time.

Be careful with accessibility when you add features. Announce the result of each check in the live region, keep the focus order logical after every change, and never use a timer without a way to pause or extend it. A quiz that people with disabilities cannot finish is not a good quiz, whatever the questions are.

Keeping the quiz honest

A quiz teaches only when the feedback is trustworthy, so check your own questions the way you would check code. Make sure each question has exactly one defensible correct answer, that the wrong choices are plausible rather than silly, and that the explanation says why, not only what. Avoid choices like "all of the above", which reward guessing. Review the questions by reading them aloud, because awkward wording shows up quickly when you hear it. When a learner gets one wrong, the explanation is the lesson, so it deserves as much care as the question.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.