Facing issues with Javascript coding quiz calculations

I've been working on a quiz that is supposed to tally the correct and incorrect answers. However, no matter how many correct answers I input, both arrays always show a result of 0. It seems like there must be an issue in the evaluate function at the end. Appreciate any help on this matter.

var responsesArray= [];
var correct=[];
var incorrect= [];

function question2() {

  var firstQuestion = prompt('Does null === 0 ? (Yes or No)')

// why do you need to convert the answer to lowercase?
  if (firstQuestion.toLowerCase() === 'yes') {
    firstQuestion = true
  } else if (firstQuestion.toLowerCase() === 'no') {
    firstQuestion = false
  } else {
// what if the user writes something other than yes or no? 
// they will have to answer the question again
    alert("Please answer either Yes or No");
    return question2();
  }
  responsesArray.push(firstQuestion); // add the true or false value to the responses array
}

question2();

function question3() {
  var js = prompt('What was the original name for JavaScript: Java, LiveScript, JavaLive, or ScriptyScript?');
  js = js.toLowerCase();
  switch (js) {
    // your own answers
    
    case "livescript":
    console.log("Correct!");
    break;
    case "Java":
    console.log("wrong");
    break;
    case "JavaLive":
    console.log("wrong");
    break;
    case "ScriptyScript":
    console.log("wrong");
    break;
  default:
    console.log("Sorry the answer is LiveScript");
  }
  responsesArray.push(js);
  
  var mine = prompt('What coding language is exclusively related to the back-end: Ruby, JavaScript, HTML?');
  mine= mine.toLowerCase();
  switch (mine) {
    // your own answers
  case "ruby":
    console.log("Yeah!");
    break;
    case "html":
    console.log("ouuu I'm sorry for you");
    break;
    case "javascript":
    console.log("Yeah but so so");
    break;
  }
  responsesArray.push(mine);
}

question3();

function evaluate(responsesArray) {

for (var i = 0; i < responsesArray.length; i++) {
if (responsesArray[i] === true || responsesArray[i] === "livescript" || responsesArray[i] === "ruby") {
      correct++;

    } else{
      if (responsesArray[i] !== true || responsesArray[i] !== "livescript" || responsesArray[i] !== "ruby") {
      incorrect++;
    }
}
}

Answer №1

Utilize an array to store the correct response and then compare it with the user's answer to easily determine its accuracy.

Take a look at the code snippet below.

var responsesArray = [];
var correct = 0;
var incorrect = 0;
// Initialize the correct answer
var index = 0;
// Array to hold correct answers
var correctAnswers = [];


function question2() {
  // Save the correct answer
  correctAnswers[index++] = "yes";
  var firstQuestion = prompt('Does null === 0? (Yes or No)')

  if (firstQuestion.toLowerCase() === 'yes') {
    console.log("correct");
    firstQuestion = 'yes'
  } else if (firstQuestion.toLowerCase() === 'no') {
    console.log("incorrect");
    firstQuestion = 'no'
  } else {
    alert("Please answer either Yes or No");
    return question2();
  }
  responsesArray.push(firstQuestion);
}

question2();


function question3() {
  // Save the correct answer
  correctAnswers[index++] = "livescript";
  var js = prompt('What was the original name for JavaScript: Java, LiveScript, JavaLive, or ScriptyScript?');
  js = js.toLowerCase();
  switch (js) {      
      // your own answers

    case "livescript":
      console.log("Correct!");
      break;
    case "Java":
      console.log("wrong");
      break;
    case "JavaLive":
      console.log("wrong");
      break;
    case "ScriptyScript":
      console.log("wrong");
      break;
    default:
      console.log("Sorry the answer is LiveScript");
  }
  responsesArray.push(js);

  //Save correct answer.
  correctAnswers[index++] = "ruby";
  var mine = prompt('What coding language is exclusively related to the back-end: Ruby, JavaScript, HTML?');
  mine= mine.toLowerCase();
  switch (mine) {
      // your own answers
    case "ruby":
      console.log("Yeah!");
      break;
    case "html":
      console.log("ouuu I'm sorry for you");
      break;
    case "javascript":
      console.log("Yeah but so so");
      break;
  }
  responsesArray.push(mine);
  //Call function to evaluate correct or incorrect answer
  evaluate(responsesArray, correctAnswers)
}

question3();

function evaluate(responsesArray, correctAnswers) 
{
  for (var i = 0; i < responsesArray.length; i++) 
  {
    if (responsesArray[i] === correctAnswers[i]) 
    {
      correct++;
    } else {
      if (responsesArray[i] !== correctAnswers[i]) {
        incorrect++;
      }
    }
  }
  alert("Correct : "+ correct +" and Incorrect : "+ incorrect);
}

Answer №2

Your method of testing for correct answers needs improvement. Instead, create an array containing the correct answers and check them using the following approach:

var correct = incorrect = 0; // Make sure to initialize your variables 

function evaluate(responsesArray) {
  var correctAnswers = [true,"livescript","ruby"];
  for (var i = 0; i < responsesArray.length; i++) {
    if (responsesArray[i] === correctAnswers[i]) {
      correct++;
    } else {
      incorrect++;
    }
  }
}

Your previous code looked like this:

if (responsesArray[i] === true|| "livescript" || "ruby"){

This actually means:

If the response is true, or if 'livescript' is considered true, or if 'ruby' is considered true, then

Since JavaScript treats strings as truthy values, the if statement would always be true.

It's also unnecessary to have a second if statement, as the else part will only run if the first condition is false, meaning you've already filtered out incorrect answers.

Lastly, make sure to define your counter variables before incrementing them. While it may work without this step, not incrementing one variable could leave it undefined after calling evaluate. It's good practice to always define your variables.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing a hierarchical data retrieval system in MongoDB with Node.js to retrieve data in the format of Category > Subcategory > Product

I have 3 unique models that are interrelated and I would like to connect them by their respective IDs. The desired response is provided below. Below is a sample dataset for reference: This is the JSON format I require in the response "categoryData": ...

The Tri-dimensional.js StereoEffect

I'm unsure why it isn't functioning properly. I've included: var effect = new THREE.StereoEffect(renderer); effect.eyeSeparation = 10; effect.setSize(window.innerWidth, window.innerHeight); console.log("aspect ratio is " + window.innerWidt ...

Setting up webpack encore for async and await in a Symfony 4 and VueJs project

After setting up a VueJs project within Symfony 4, I encountered an unexpected error involving await and async (Uncaught ReferenceError: regeneratorRuntime is not defined) I've come across plenty of resources for webpack, but nothing specifically for ...

What methods are available to gradually increase a counter until it reaches a specific number by a designated date?

I have a unique idea for my website - I want to create a special counter that gradually increases to a specific number, but does so over the course of an entire year. Imagine starting at 0 and aiming to reach 35340340 after exactly one year has passed. It ...

Attempting to incorporate an audio file into a Discord.js module

My bot can join the voice channel successfully, but when I attempt to play audio, I encounter multiple errors indicating that I am missing certain modules [@discordjs/opus, node-opus, opusscript]. Although I have installed these modules, I am unsure of w ...

How can you prevent multiple instances of JavaScript objects from being disposed of after they have completed their task?

I'm facing an issue with the code snippet below: $(document).ready(function() { $('.container').ready(function() { var v = new Video($(this)); v.load(); }); }); I'm trying to prevent the object 'v&apos ...

Do you think it's essential to utilize express for node in developing moderate-sized applications?

What is the best approach for handling cookies and authentication in a project with approximately 30 or 40 routes? Is it feasible to manage cookies and authentication without using Express? What percentage of developers prefer using Express over bare bon ...

Stop AJAX Submission When Data is Empty

I've been struggling to implement client-side validation to prevent form submission if an object is empty. Despite my efforts, I haven't found a satisfactory solution yet. Here is an excerpt of my form submission Javascript: $(document).ready(f ...

Trouble with closing Bootstrap 4 modal

My Bootstrap 4 modal is causing issues as it pops up on button click but won't close unless I refresh the page. I've been attempting to get it to close by clicking the 'close' button or simply by clicking anywhere on the main page body. ...

single calendar bootstrap-datepicker allowing users to select date ranges

Is it possible to create a single calendar range date picker with Bootstrap instead of using two separate calendars? Currently, I have implemented a solution with two calendars. $('#datepicker').datepicker({ }); <link href="https://cdnjs.cl ...

Manipulating the InnerHTML content of a total of 144 individual cells

I am currently developing a tile-based game using tables. Each td cell contains the following code: <td> <div id="image" style="display:none; display: fixed; right: 5; top:2;"><img src="http://thumb7.shutterstock.com/display_pic_with_logo ...

How should you correctly display the outcome of a mathematical function on a data property in a v-for loop in VueJS?

Recently, I've been developing a dice roller using Vue for a game project. The approach involves looping through different types of dice with v-for to create buttons and display the result in an associated div element. However, despite correct console ...

How can I efficiently store and access DOM elements in my React application to avoid constant re-fetching?

Is there a known pattern for storing references to both regular DOM elements and jQuery elements within a class? Despite the general advice against using jQuery with React, I needed the jQuery functions for my menu to function properly and did not have ti ...

Retrieve a data value from a JSON object by checking if the ID exists within a nested object

I am facing the challenge of navigating through a JSON object where child objects contain IDs that need to be matched with parent properties. The JSON structure looks like this: { id: 1, map: "test", parameter_definitions: [{ID: 1, pa ...

Implement Next.js deployment on NGINX server with a 403 forbidden error

I am currently utilizing Next.js for the frontend and Django for the backend. During development, everything is functioning properly. However, when transitioning to production, I am encountering a 403 Forbidden Error related to /_next/static/chunks. It app ...

Encountering the "Local resource can't be loaded" error when attempting to link a MediaSource object as the content for an HTML5 video tag

I'm attempting to make this specific example function properly. Everything runs smoothly when I click the link, but I encounter an error when trying to download the HTML file onto my local machine and repeat the process. An error message pops up sayi ...

TypeB should utilize InterfaceA for best practice

I have the following TypeScript code snippet. interface InterfaceA { id: string; key: string; value: string | number; } type TypeB = null; const sample: TypeB = { id: '1' }; I am looking for simple and maintainable solutions where TypeB ...

Tips for seamlessly incorporating WalletConnect into your decentralized app with the help of web3-react

I have been working on integrating WalletConnect into my project by referring to the documentation provided by web3-react. The configuration settings I am using for the connector are as follows: import { WalletConnectConnector } from '@web3-react/wal ...

Getting all inline styles from an HTML string using JavaScript

(JavaScript) I am working with an html email template stored as a string. Is there a way to extract all the inline styles used in the template? For instance, if I have this input: <div style="min-width:300px;max-width:600px;overflow-wrap:break-word ...

Interested in developing a C++ program that utilizes a two-dimensional pointer to store values in groups of three?

Hey, I have this code snippet that I've been working on. It involves using an if-else condition to store values in two 2-D pointers called *p and *q. Everything seems to be running fine but for some reason, I'm having trouble printing out the val ...