Course Content
Data types and Values
0/1
Object-oriented programming in JavaScript
0/1
Error handling and debugging in JavaScript
0/1
JavaScript functions for string and array manipulation
0/1
JavaScript Libraries and Frameworks
0/1
JavaScript
About Lesson

Building a Quiz Game in JavaScript

  

Question: Imagine you are tasked with building a quiz game in JavaScript. The game should display questions, allow the user to choose answers, calculate the score, and provide feedback. Here’s what you need to accomplish:

  

  1. Create an array of question objects, each containing a question, answer options, and the correct answer.
  2.   

  3. Display each question to the user and prompt them to choose an answer using the prompt() function.
  4.   

  5. Validate the user’s input and compare it to the correct answer. Keep track of the user’s score.
  6.   

  7. Display the current score after each question.
  8.   

  9. After all questions have been answered, provide feedback to the user about their performance.
  10.   

  11. Utilize functions, loops, conditionals, and scope effectively.

          

Quiz Game: Test Your Knowledge! – SAMPLE SOLUTION

    

    //script. -- make this a script opening tag
    // Array of question objects
    var questions = [
      {
        question: "What is the capital of France?",
        options: ["Paris", "London", "Madrid"],
        correctAnswer: "Paris"
      },
      {
        question: "Which planet is known as the Red Planet?",
        options: ["Earth", "Mars", "Jupiter"],
        correctAnswer: "Mars"
      },
      {
        question: "What programming language is used for web development?",
        options: ["Python", "JavaScript", "Java"],
        correctAnswer: "JavaScript"
      }
    ];

    // Initialize score
    var score = 0;

    // Iterate through each question
    for (var i = 0; i < questions.length; i++) {
      var userAnswer = prompt(questions[i].question + "nOptions: " + questions[i].options.join(", "));
      
      // Validate user input
      if (questions[i].options.includes(userAnswer)) {
        if (userAnswer === questions[i].correctAnswer) {
          score++;
          alert("Correct! Your current score is: " + score);
        } else {
          alert("Incorrect. The correct answer is: " + questions[i].correctAnswer);
        }
      } else {
        alert("Invalid input. Please choose a valid option.");
      }
    }

    // Provide feedback to the user
    if (score === questions.length) {
      alert("Congratulations! You answered all questions correctly.");
    } else {
      alert("Your final score is: " + score + " out of " + questions.length);
    }
    //script. -- make this a script closing tag