TalentJR

🟨 JavaScript tutorial for beginners · Class 8 · Lesson 18 of 18 · Free

Capstone: Build an Interactive Quiz App in JavaScript

⏱ About 45 minutes · ▶ run real JavaScript here — nothing to install · no sign-in

In this lesson you will

  • Store quiz questions as an array of objects
  • Show a question with answer buttons and check the clicked answer
  • Move to the next question, show the final score and save the best score

Your class wants a quick GK quiz for Friday's activity period. Instead of reading questions aloud, you will build a quiz app: click an answer, see green or red at once, and get your score at the end. This capstone uses almost everything from Lessons 1–17.

How do I store quiz questions in JavaScript?

First the data. Each question is an object (Lesson 10) with three keys: the question text `q`, an `options` array, and `correct` — the **index** of the right option.

Why an index and not the answer text? Because then checking is easy: did the student click button number `correct`?

All questions go into one array, so we can go through them one by one with an index.

🎬 How JavaScript thinks — step 1 of 7JavaScript is about to run line 1
▶const questions = [
2 { q: "What is 7 × 8?", options: ["54", "56", "64"], correct: 1 },
3 { q: "Capital of India?", options: ["Mumbai", "Kolkata", "New Delhi"], correct: 2 },
4 { q: "How many players in a cricket team?", options: ["11", "9", "12"], correct: 0 }
5];
6
7console.log("Total questions:", questions.length);
8
9const first = questions[0];
10console.log(first.q);
11console.log("Options:", first.options);
12console.log("Right answer:", first.options[first.correct]);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Total questions: 3
What is 7 × 8?
Options: ["54", "56", "64"]
Right answer: 56

💡 Try it: add a fourth question of your own and print questions.length again.

How do I check answers and keep a score in JavaScript?

The brain of the quiz is one function: `checkAnswer(qIndex, choice)`. If the choice matches `correct`, the score goes up by 1.

`score` lives **outside** the function, so it remembers its value between calls. If it were inside, it would start at 0 every time.

Here we pretend a student picked options 1, 0 and 0. Watch the score change in the animation.

🎬 How JavaScript thinks — step 1 of 17JavaScript is about to run line 1
▶const questions = [
2 { q: "What is 7 × 8?", options: ["54", "56", "64"], correct: 1 },
3 { q: "Capital of India?", options: ["Mumbai", "Kolkata", "New Delhi"], correct: 2 },
4 { q: "How many players in a cricket team?", options: ["11", "9", "12"], correct: 0 }
5];
6let score = 0;
7
8function checkAnswer(qIndex, choice) {
9 const right = choice === questions[qIndex].correct;
10 if (right) score++;
11 console.log(`Q${qIndex + 1}: ${right ? "✅ right" : "❌ wrong"}`);
12}
13
14const picks = [1, 0, 0];
15picks.forEach((choice, i) => checkAnswer(i, choice));
16console.log(`Score: ${score}/${questions.length}`);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Q1: ✅ right
Q2: ❌ wrong
Q3: ✅ right
Score: 2/3

How do I show a question with answer buttons on the page?

Now the screen. `showQuestion(i)` writes the question into the heading. Then it makes one `<button>` per option with `createElement` (Lesson 15 used the same idea for `<li>`).

Each button gets a click listener that remembers its own index `n`. For now it just logs which option you clicked.

Try it: change `showQuestion(0)` to `showQuestion(2)`.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Showing: What is 7 × 8?

How do I show right or wrong when an answer is clicked?

Good quizzes give feedback at once. When a button is clicked, we colour it green or red with a class. We also colour the correct button green, so the student learns the answer.

Then we **disable** all buttons. Otherwise a student could click again and again to collect points!

Click a wrong answer first and watch what happens.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Click an answer

How do I build the full JavaScript quiz app with next question and final score?

Now we join all the pieces. A variable `current` remembers which question we are on. After each answer, a **Next** button shows the next question.

When `current` reaches `questions.length`, there are no more questions, so we show the score instead.

Play the whole quiz. Then press ▶ Run to play again.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Quiz ready: 3 questions

💡 Try it: add your own questions to the array — the app needs no other change.

How do I save the best score with localStorage?

A final touch from Lesson 13: remember the best score, so players try to beat it.

After the quiz, compare the new score with the saved best. If it is higher, save it. We also turn the score into a percentage with `Math.round`.

This part is plain logic, so you can test it in the console. Then copy the `finish()` function into the quiz above.

🎬 How JavaScript thinks — step 1 of 19JavaScript is about to run line 1
▶localStorage.removeItem("quizBest"); // start fresh for this test
2
3function finish(score, total) {
4 const percent = Math.round((score / total) * 100);
5 const best = Number(localStorage.getItem("quizBest"));
6 if (score > best) {
7 localStorage.setItem("quizBest", score);
8 console.log(`${score}/${total} (${percent}%) — 🏆 new best!`);
9 } else {
10 console.log(`${score}/${total} (${percent}%) — best is ${best}`);
11 }
12}
13finish(2, 3);
14finish(1, 3);
15finish(3, 3);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
2/3 (67%) — 🏆 new best!
1/3 (33%) — best is 2
3/3 (100%) — 🏆 new best!

🤔 Predict the output

Think like JavaScript: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

const item = { q: "2 + 2?", options: ["3", "4", "5"], correct: 1 };
console.log(item.options[item.correct]);

Question 2. What does this print?

const correct = [1, 2, 0];
const picks = [1, 0, 0];
let score = 0;
for (let i = 0; i < picks.length; i++) {
  if (picks[i] === correct[i]) score++;
}
console.log(score);

Question 3. What does this print?

const score = 2;
const total = 3;
console.log(Math.round((score / total) * 100) + "%");

🧩 Your challenge

Write a **quiz report card**. For each question, compare the student's pick with `correct`. Print ✅ for right, or ❌ with the right answer. Then print the score and a message: "Excellent!" for full marks, "Good try!" for at least half, otherwise "Keep practising!". Expected output: ``` Q1 ✅ Q2 ❌ (answer: New Delhi) Q3 ✅ Q4 ✅ Score: 3/4 — Good try! ```

Expected output in the console:
Q1 ✅
Q2 ❌ (answer: New Delhi)
Q3 ✅
Q4 ✅
Score: 3/4 — Good try!
🟨 JavaScript — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

const item = { q: "7 × 8?", options: ["54", "56", "64"], correct: 1 };
let score = 0;
const clicked = "56";
if (clicked === item.correct) score++;
console.log("Score:", score);

No error, but the score stays 0 even for the right answer, because the text "56" is never === the number 1.

✅ Right

const item = { q: "7 × 8?", options: ["54", "56", "64"], correct: 1 };
let score = 0;
const clicked = "56";
if (clicked === item.options[item.correct]) score++;
console.log("Score:", score);

correct is an index (a number), but clicked is the answer text. Compare text with text: item.options[item.correct].

❌ Wrong

function checkAnswer(choice, correct) {
  let score = 0;
  if (choice === correct) score++;
  return score;
}
checkAnswer(1, 1);
console.log("Final score:", checkAnswer(2, 2));

No error, but the final score is 1 instead of 2: the score starts again from 0 on every answer.

✅ Right

let score = 0;
function checkAnswer(choice, correct) {
  if (choice === correct) score++;
  return score;
}
checkAnswer(1, 1);
console.log("Final score:", checkAnswer(2, 2));

A let inside the function is made fresh, as 0, on every call. Keep score outside the function so it remembers.

❌ Wrong

const questions = [{ q: "7 × 8?" }, { q: "Capital of India?" }];
let current = 0;
current++;
current++;
console.log(questions[current].q);

TypeError: Cannot read properties of undefined (reading 'q')

✅ Right

const questions = [{ q: "7 × 8?" }, { q: "Capital of India?" }];
let current = 0;
current++;
current++;
if (current < questions.length) {
  console.log(questions[current].q);
} else {
  console.log("Quiz over!");
}

With 2 questions, the last index is 1. Always check current < questions.length before you read a question.

📌 Remember

  • Store each question as an object: { q, options, correct } with correct as an index.
  • Make one button per option with createElement and a click listener.
  • Keep score and current outside functions so they remember their values.
  • Disable buttons after a click, and show right or wrong with classes.
  • When current reaches questions.length, show the final score — and save the best with localStorage.

Finished the quiz and the challenge?

Questions students ask

How do I make a quiz in JavaScript?

Put the questions in an array of objects. Write a function that shows one question and creates answer buttons. On click, check the answer, update the score, and move to the next question until the array ends.

How do I add a timer to my quiz?

Use setInterval from Lesson 14. Start it in showQuestion(), count down every second, and when it reaches 0, count the question as wrong and move on. Always clearInterval before starting the next one.

How do I shuffle the quiz questions?

You can sort the array in a random order, for example with a small shuffle loop that swaps items using Math.random(). Then every player gets a different order.

What can I build after this JavaScript course?

Try a flashcard app, a times-table game or a score board for your class cricket match. In Class 9 you will learn classes, fetch and APIs, so your apps can load real data.