How to make a quiz on JavaScript

Learn how to create a JavaScript quiz with an example, including planning and implementation steps.

Creating a quiz using JavaScript can be a great way to test user knowledge and keep track of scores. There are several ways to do this, but one of the most effective and straightforward methods is to use a JavaScript object to store the questions, answers, and scores.

Creating the Questions Object

The first step is to create a JavaScript object that will store the quiz questions and answers. This object will contain the questions, the possible answers, and the correct answer. We'll also include a key to store the user's score.

var quiz = {
  questions: [
    {
      prompt: "What is the capital of France?",
      options: ["Paris", "Marseille", "Lyon", "Nice"],
      correctAnswer: "Paris"
    },
    {
      prompt: "What is the capital of Germany?",
      options: ["Berlin", "Frankfurt", "Munich", "Hamburg"],
      correctAnswer: "Berlin"
    },
    {
      prompt: "What is the capital of Italy?",
      options: ["Rome", "Milan", "Naples", "Turin"],
      correctAnswer: "Rome"
    }
  ],
  score: 0
};

Creating the Quiz Function

Now that we have our questions object, we can create a function to display the questions and keep track of the user's score. This function will loop through the questions in the object and display them one at a time. It will also check the user's answer to see if it matches the correct answer. If so, it will increase the user's score by one.

function showQuiz() {
  // loop through each question
  for (var i = 0; i < quiz.questions.length; i++) {
    // get the current question
    var question = quiz.questions[i];
    
    // display the prompt
    console.log(question.prompt);
    
    // loop through each option
    for (var j = 0; j < question.options.length; j++) {
      console.log(j + ": " + question.options[j]);
    }
    
    // get the user's answer
    var answer = prompt("Enter your answer:");
    
    // check if the answer is correct
    if (answer == question.correctAnswer) {
      // increase the user's score
      quiz.score++;
    }
  }
  
  // display the user's score
  console.log("Your score: " + quiz.score);
}

Once the function is defined, we can call it to start the quiz:


showQuiz();

The function will loop through the questions and display each one with its options. It will then prompt the user for their answer and check if it matches the correct answer. If it does, it will increase the user's score and move on to the next question. When all of the questions have been answered, it will display the user's score. By using a JavaScript object to store the questions and answers, and a function to handle the quiz logic, we can easily create a quiz using JavaScript. This approach makes it easy to add, modify, and remove questions from the quiz, and to keep track of the user's score.

Answers (0)