Skip to main content

Building a Quiz App with Vanilla JavaScript

Updated 4 min readMarkdown

A quiz shows a question, waits for an answer, keeps score and moves on. The key idea is this: build the screen once, then fill it with different data for each question.

This post walks through a small quiz with four options per question, a Submit button and a final score.

The idea

The page has only one question card. When you submit an answer, JavaScript swaps the text inside it. Two numbers track your progress:

  • currentIndex: which question you are on.
  • score: how many you have answered correctly.

Keeping the questions separate

The questions live in their own file, questionBank.js, as an array of objects:

const questionsBank = [
  {
    id: 1,
    question: 'iPhone belongs to which company',
    option1: 'Apple',
    option2: 'Samsung',
    option3: 'Nokia',
    option4: 'Motorola',
    correct: 'Apple'
  },
  {
    id: 2,
    question: 'The capital of India is',
    option1: 'Mumbai',
    option2: 'Delhi',
    option3: 'Kolkata',
    option4: 'Chennai',
    correct: 'Delhi'
  }
]

export default questionsBank;

To add a question, you add an object. The quiz logic stays the same.

The main script imports this array:

import questionsBank from './questionBank.js';

For import to work, the HTML must load the script as a module:

<script type="module" src="app.js"></script>

Modules don't load when you open the file directly from your computer, so run it through a local server.

The HTML: one reusable card

<div class="questions">
  <h2 id="question">Test question</h2>
  <ul id="questionsList">
    <li>
      <input type="radio" id="option1" name="answers">
      <label id="option1_text">Option 1</label>
    </li>
    <!-- option2, option3 and option4 follow the same pattern -->
  </ul>
</div>
<div class="submit">
  <button id="onSubmit">Submit</button>
</div>

All four radio buttons share name="answers". That makes them one group, so only one can be selected at a time. The text in the markup is a placeholder that JavaScript replaces.

The JavaScript

1. Load a question

const loadQuiz = () => {
  const currentQuestion = questionsBank[currentIndex];

  question.innerHTML = currentQuestion.question;
  document.querySelector("#option1").value = currentQuestion.option1;
  document.querySelector("#option1_text").innerHTML = currentQuestion.option1;
  // the same two lines repeat for options 2, 3 and 4
}

Each option is set twice. The value is what the code compares, and the label text is what you read.

2. Find the selected answer

const isQuestionSelected = () => {
  let answer;

  answers.forEach(item => {
    if (item.checked) {
      answer = item;
    }
  })

  return answer;
}

This returns the checked radio button. If nothing is checked, it returns undefined.

3. Handle Submit

onSubmit.addEventListener("click", () => {
  // if radio button is not selected, don't submit
  const answer = isQuestionSelected();

  if (answer) {
    if (answer.value === questionsBank[currentIndex].correct) {
      score++;
    }
    currentIndex++; 
  };
  // after submit, remove radio selected value
  unselectOptions();
  // total score after end of quiz
  if (currentIndex > (questionsBank.length - 1)) {
    question.innerHTML = `<h2>You have answered ${score} out of ${questionsBank.length} questions.</h2>`;
    document.querySelector("#questionsList").style.display = 'none';
    onSubmit.innerHTML = `<a onclick="location.reload()">Reload</a>`;
  } else {
    loadQuiz();
  }
})

In order, it does this:

  1. Checks that an option is selected. If not, you stay on the same question.
  2. Adds a point if the answer is correct.
  3. Moves to the next question.
  4. Clears the selection, using the small unselectOptions function.
  5. Shows the next question, or the final score if none are left.

The script ends by calling loadQuiz() once, so the first question appears when the page opens.

What I would improve next

  • Clickable labels: add for="option1" and so on, so clicking the text selects the option.
  • Options as an array: replace option1 to option4 with options: [...] and create the list in a loop.
  • Safer rendering: use textContent instead of innerHTML. A question such as "What does <div> do?" would then display correctly.
  • Cleaner result screen: the score is an h2 placed inside another h2. Plain text is enough.
  • Restart without reloading: reset currentIndex and score, then call loadQuiz().
  • Feedback: show which answers were right or wrong.

About the author

  • I am a Frontend Engineer with a particular interest in developing Web Applications. I am a JavaScript enthusiast.

No comments yet. Be the first to comment.