Explain it simply
Explain it simply
A Quiz App is like a teacher flipping through a stack of question cards one at a time. The teacher has to remember which card is showing, whether the student has already answered it, and how many points they have so far. Only after an answer does the next card turn over, and when the cards run out, the result is announced.
In JavaScript, that teacher's notebook is a state object. The buttons and text on screen are just pictures drawn from that state. The rules, such as when to award a point and when moving forward is allowed, live on the state side only.
Problem → Why → Solution
The problem: everything lives in one click handler
In the draft below, counting the score, moving to the next question and drawing the buttons are all tangled inside one click handler. It seems to work when you try it, but four bugs are hiding.
A quick double click on the right answer adds two points and also skips a question. Because of the data-correct="true" attribute, anyone can right-click, choose Inspect, and read the answer. After the last question, questions[3] is undefined, so render() crashes. And since the choice text goes in through innerHTML, a choice such as "<img onerror=...>" would run as HTML.
let score = 0;
let index = 0;
function render(q) {
quizEl.innerHTML = q.choices
.map((c, i) => `<button data-correct="${i === q.correctIndex}">${c}</button>`)
.join(""); // "Inspect element" shows which button is correct
}
quizEl.addEventListener("click", (event) => {
if (event.target.dataset.correct === "true") score++; // double click = 2 points
index++;
render(questions[index]); // after the last one: questions[3] is undefined
});Why do these bugs appear?
The quiz's rules are not written down anywhere. "An answered question cannot be answered again", "you cannot move on before answering" and "when questions run out, show the result" are not part of any state, so every click is free to do anything.
Core concept: a quiz is a small state machine
A state machine is a system with only a few situations (states), where you can move from one to another only through defined actions. This quiz's state fits in four values: index (which question), score, answered (has this question been answered yet) and history (what was chosen). Whether the quiz is finished does not need storing at all; it can be computed from index >= items.length.
| Action | Allowed when | State change |
|---|---|---|
| submit(choice) | answered is false and not finished | score++ if right, answered = true, push to history |
| next() | answered is true | index++, answered = false |
| results() | Any time | None; it only reads |
The "allowed when" column is what fixes the bugs from the problem section. submit() returns early when the question is already answered, so a double click cannot score twice. next() refuses to advance while answered is false, so nobody skips a question without answering. Checking isFinished() before rendering means the UI never tries to draw an undefined question.
The answer is stored by value (answer: "const"), not by position (correctIndex: 1), so reordering the choices cannot break grading. Finally, percent stays a number while the grade is decided; toFixed(1) returns a string, so it is used only at the moment of display.
Notice what the state leaves out
The state holds no button elements, no CSS classes and no innerHTML. Because the DOM stays outside, one createQuiz() can drive a web page, a terminal version and a test suite, each simply reading current() and results(). It also keeps new features cheap. A timer, a skip rule or a "retry the wrong ones" mode becomes one more guarded action in the table above instead of another tangle of if statements inside a click handler. If you can write down in that table when each action is allowed, you are ready to write the code.
- Question data is the card stack
- The state object is the notebook
- submit and next are guarded doors
- The UI only draws the notebook
The UI never changes the score itself; it calls submit() and shows whatever message and state come back.
General pattern
function createFlow(items) {
const state = { index: 0, answered: false };
return {
current: () => items[state.index],
submit(input) { if (state.answered) return; state.answered = true; /* score */ },
next() { if (state.answered) { state.index++; state.answered = false; } },
isFinished: () => state.index >= items.length,
};
}A factory function keeps the state hidden in a closure and exposes only guarded methods. Each method first checks whether its action is allowed, and only then changes the state.
Run the quiz logic, double click included
This file never touches the DOM. The loop simulates the user's clicks and adds one double click on the first question. In the output, check that the second click is ignored and that the final score stays at 2/3.
// quiz.js - quiz rules with no DOM. The page renders whatever state says.
const questions = [
{ id: "q1", text: "What does JS stand for?",
choices: ["Java Source", "JavaScript", "JSON"], answer: "JavaScript" },
{ id: "q2", text: "Which keyword declares a constant?",
choices: ["let", "var", "const"], answer: "const" },
{ id: "q3", text: "What is 2 + 2?", choices: ["4", "22", "5"], answer: "4" },
];
function createQuiz(items) {
const state = { index: 0, score: 0, answered: false, history: [] };
function current() {
return items[state.index];
}
function submit(choice) {
if (state.answered || isFinished()) return "Ignored: already answered";
const q = current();
const correct = choice === q.answer;
if (correct) state.score++;
state.answered = true;
state.history.push({ id: q.id, choice, correct });
return correct ? "Correct!" : `Wrong. The answer is ${q.answer}`;
}
function next() {
if (!state.answered) return false; // must answer before moving on
state.index++;
state.answered = false;
return true;
}
function isFinished() {
return state.index >= items.length;
}
function results() {
const percent = (state.score / items.length) * 100; // a number, not a string
let grade = "Needs practice";
if (percent >= 90) grade = "Excellent";
else if (percent >= 70) grade = "Good";
else if (percent >= 50) grade = "Pass";
const shown = percent.toFixed(1); // format only for display
return { score: state.score, total: items.length, percent: shown, grade };
}
return { current, submit, next, isFinished, results };
}
const quiz = createQuiz(questions);
const picks = ["JavaScript", "let", "4"];
for (const pick of picks) {
console.log(`${quiz.current().text} -> ${pick}`);
console.log(" " + quiz.submit(pick));
if (pick === "JavaScript") console.log(" " + quiz.submit(pick)); // a double click
quiz.next();
}
const r = quiz.results();
console.log(`Score: ${r.score}/${r.total} (${r.percent}%) - ${r.grade}`);Code breakdown
- All state in one place
const state = { index: 0, score: 0, answered: false, history: [] };The state lives inside createQuiz()'s closure, so outside code cannot write state.score = 100. The only way to change it is through submit() and next().
- The double-click guard
if (state.answered || isFinished()) return "Ignored: already answered";The first click sets answered to true. When the second click arrives it exits on this line, so the score does not move.
- Grade by value
const correct = choice === q.answer;It compares the chosen text with answer instead of a button position, so reordering the choices never requires changing this line.
- No skipping
if (!state.answered) return false; // must answer before moving onCalling next() on an unanswered question returns false and leaves index alone. The UI can use that return value to keep a Next button disabled.
- Decide with numbers, format at the end
const shown = percent.toFixed(1); // format only for displayThe grade is decided on the number 66.666... and only then is the string "66.7" produced. Comparing that string with >= 90 would happen to work through coercion, but only by accident.
What does JS stand for? -> JavaScript
Correct!
Ignored: already answered
Which keyword declares a constant? -> let
Wrong. The answer is const
What is 2 + 2? -> 4
Correct!
Score: 2/3 (66.7%) - PassWiring it to the page
The browser side only draws the state. Choice text goes in through textContent, so it can never run as HTML, and no attribute on a button reveals the right answer. Disabling every button after one click is the UI's defence, while the guard inside submit() is the logic's defence.
Keep in mind that the whole questions array is shipped to the browser, so anyone who reads the source can find the answers. That is fine for a practice quiz, but a graded exam must check answers on the server.
// ui.js - browser only: draws the quiz state; it never decides the score
const box = document.querySelector("#quiz");
const feedback = document.querySelector("#feedback");
const quiz = createQuiz(questions);
function render() {
if (quiz.isFinished()) {
const r = quiz.results();
box.textContent = `Score: ${r.score}/${r.total} (${r.percent}%) - ${r.grade}`;
return;
}
const q = quiz.current();
const buttons = q.choices.map((choice) => {
const button = document.createElement("button");
button.textContent = choice; // plain text: no HTML injection, no hidden answer
button.addEventListener("click", () => {
feedback.textContent = quiz.submit(choice);
buttons.forEach((b) => (b.disabled = true));
setTimeout(() => {
quiz.next();
feedback.textContent = "";
render();
}, 800);
});
return button;
});
box.replaceChildren(document.createTextNode(q.text), ...buttons);
}
render();In real projects
In real projects
Language-learning apps, company onboarding quizzes and flashcard apps all use this index/score/answered shape. Because the logic is made of pure functions, rules such as "a double click never scores twice" and "after the last question the quiz is finished" can be unit tested without opening a browser.
Think about accessibility too. Choices rendered as radio buttons inside a fieldset with a legend can be picked with the arrow keys, and screen readers announce the question. Feedback like "Correct!" placed in an element with aria-live="polite" is read out automatically. If the quiz has a timer, call clearInterval() as soon as it finishes; otherwise the timer keeps running in the background and may change a quiz that is already over. Saving progress in localStorage lets the learner continue after a page refresh.
Common mistakes
Common mistakes
Shuffling choices but grading by correctIndex
If you shuffle the choices and keep correctIndex: 1, a different choice now sits at index 1. People who pick the right answer lose the point while a wrong pick may earn it. Store the answer by value, or give every choice an id.
Incrementing score directly in the click handler
Writing score++ in the handler means every click awards a point. A double click, pressing Enter twice, or a touch and a mouse event firing together can all inflate the score. Change the score only inside a guarded submit().
Doing maths with the result of toFixed()
toFixed() returns a string, so "66.7" + 10 produces "66.710". Compute grades, averages and rankings with numbers, and format only when the value goes on screen.
Mini challenge
Shuffle the choices and add a review
Write shuffle() using the Fisher-Yates method, prepareQuestion() which returns a new question with shuffled choices, and review() which lists the questions answered wrongly. A seeded random generator makes the order identical on every run.
- shuffle() returns a new array and leaves the original untouched
- random arrives as a parameter (do not call Math.random directly)
- After shuffling, answers are still graded by the chosen text
- review() returns one line per wrong entry
// Given: a seeded generator, so the "random" order is the same on every run.
function seededRandom(seed) {
let s = seed;
return () => {
s = (s * 16807) % 2147483647;
return (s - 1) / 2147483646;
};
}
function shuffle(array, random) {
// TODO: copy the array first - the caller's array must keep its order
// TODO: Fisher-Yates: walk i from the last index down to 1,
// pick j = Math.floor(random() * (i + 1)), swap copy[i] and copy[j]
}
function prepareQuestion(question, random) {
// TODO: return a new question object whose choices are shuffled
}
function review(history, items) {
// TODO: for each wrong entry return "q2: you chose null, correct is object"
}
// TODO: shuffle a 3-question bank with seededRandom(42), print each order,
// score three clicks by choice text, then print the review linesExpected: With seed 42, q1's order is "unshift | shift | pop | push", the score is 2/3, one review line appears (for q2), and the original q1 order is still push,pop,shift,unshift.
Show hint
In Fisher-Yates, i counts down from the last index to 1; pick j between 0 and i inclusive and swap with [copy[i], copy[j]] = [copy[j], copy[i]]. For the review, filter() the history and map() each wrong entry to a sentence.
Show solution
// Seeded generator (Park-Miller): the same seed gives the same "random" order.
function seededRandom(seed) {
let s = seed;
return () => {
s = (s * 16807) % 2147483647;
return (s - 1) / 2147483646;
};
}
function shuffle(array, random) {
const copy = [...array]; // never reorder the caller's array
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;
}
function prepareQuestion(question, random) {
return { ...question, choices: shuffle(question.choices, random) };
}
function review(history, items) {
return history
.filter((h) => !h.correct)
.map((h) => {
const q = items.find((item) => item.id === h.id);
return `${q.id}: you chose ${h.choice}, correct is ${q.answer}`;
});
}
const bank = [
{ id: "q1", text: "Which method adds to the end of an array?",
choices: ["push", "pop", "shift", "unshift"], answer: "push" },
{ id: "q2", text: "typeof null is...", choices: ["null", "object", "undefined"],
answer: "object" },
{ id: "q3", text: "Which compares without type coercion?",
choices: ["==", "===", "="], answer: "===" },
];
const random = seededRandom(42);
const prepared = bank.map((q) => prepareQuestion(q, random));
prepared.forEach((q) => console.log(`${q.id}: ${q.choices.join(" | ")}`));
// The learner clicks by visible text, so shuffling cannot break scoring.
const clicks = ["push", "null", "==="];
const history = prepared.map((q, i) => ({
id: q.id,
choice: clicks[i],
correct: clicks[i] === q.answer,
}));
const score = history.filter((h) => h.correct).length;
console.log(`Score: ${score}/${bank.length}`);
review(history, bank).forEach((line) => console.log("Review " + line));
console.log("Original q1 order kept:", bank[0].choices.join(","));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Treat a quiz as a small state machine: index, score, answered, history
- The answered guard in submit() stops double clicks from scoring twice
- Storing answers by value keeps grading correct after a shuffle
- Decide grades on the number and call toFixed() only for display
- The UI only draws state with textContent; real exams grade on the server
MDN — JavaScript Guide — MDN Web Docs