Asking only to re-answer incorrectly answered questions in an array using JavaScript prompts and loops. How can this be achieved without asking to repeat the entire loop?

Goals :

  1. To require the user to input the displayed words in the designated fields.
  2. To validate if the typed words are an exact match to those requested.
  3. If correct, proceed to the next word.
  4. If incorrect, prompt the user to retype the wrongly entered word.

All the words are stored in an array.

Achievements so far :

Goals 1 to 3 have been successfully met!

Challenges faced :

Goal 4 is partially achieved. The issue lies in restarting the entire loop instead of keeping track of progress and resuming from the incorrectly answered question.

The code snippet :

 wordList = ["Cachalot", "Pétunia", "Serviette"]
 score = 0
  for (let i=0; i<wordList.length; i++){
        let typedWord = prompt("Please type the following word: " + wordList[i])
        if(typedWord===wordList[i]){
            score+=1
            console.log(score)
        } else{
            console.log ("Please try again.")
            typeSmart()
        }

    }
}typeSmart()

I understand that calling the function restarts the whole process. However, I am unsure how to proceed differently. Should I utilize a while loop instead or in conjunction with the current for loop?

Answer №1

To ensure accurate matching of values, utilize a while loop for continuous comparison. Employing a for...of loop to iterate through the word list avoids the need to handle indexes.

function verifyWords() {
  const wordList = ["Dolphin", "Orchid", "Tablecloth"];
  let score = 0;
  
  for (const word of wordList) {
    const message = `Please retype the following word: ${word}`;
    
    while (prompt(message) !== word) {
      console.log("Please try again");
    }
    
    score += 1;
    console.log(score);
  }
}

verifyWords();

Answer №2

A more suitable approach would be to utilize a while loop. Since the number of times the word will be asked for is unknown, looping with a while loop is recommended over a for loop. for loops are typically used when the number of iterations is predetermined, which does not apply in this scenario.

To track the current word and progress through the list, increment the index of the current word (referred to as currentWordIdx in the provided code snippet) once the user types the word correctly. Additionally, ensure that you declare your variables using let or const (although var is an option, it is not the best practice), to prevent unintended global variable scope issues:

function typeSmart() {
  const wordList = ["Cachalot", "Pétunia", "Serviette"];
  let score = 0;
  let currentWordIdx = 0;
  while(currentWordIdx < wordList.length) {
    const currentWord = wordList[currentWordIdx];
    const typedWord = prompt("Please retype the following word: " + currentWord);
    if (typedWord === currentWord) {
      score += 1;
      currentWordIdx++; // move on to the next word
      console.log(score);
    } else {
      console.log("Please try again");
    }
  }
}
typeSmart();

Answer №3

To maintain the value of i in the loop until the correct answer is entered, add --i; within your else statement. This will continuously prompt the user with the same word until the correct answer is provided, achieving your intended purpose.

wordList = ["Cachalot", "Pétunia", "Serviette"]
 score = 0
  for (let i=0; i<wordList.length; i++){
        let typedWord = prompt("Please retype the following word: " + wordList[i])
        if(typedWord===wordList[i]){
            score+=1
            console.log(score)
        } else{
            console.log ("Please try again")
            --i;
        }

    }

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

Issue encountered while trying to connect to MongoDB: MongooseServerSelectionError

I am encountering an issue while attempting to establish a connection from my Node.js application to MongoDB using Mongoose. Every time I try to launch the application, I encounter the following error: "Error connecting to MongoDB: MongooseServerSele ...

Handling errors in chained promises and routes in Node.js/ExpressJS

I'm currently dealing with some confusion regarding how to handle errors when making function calls. To demonstrate this, I'll be using sequelizeJS as an example. Usually: First.Ctrl var second_ctrl = require( '../ctrl/second'); testC ...

Is there a way to eliminate a wrapper object from each element in a JSON array using JavaScript?

My knowledge of JavaScript is limited and I am facing a particular issue. The JSON document at hand looks like this: { "forecast": [ { "day-1": { "forecast_date": "2017-11-23", "morning": { "weather": { " ...

Using Javascript to remove spans that do not have an id assigned

Is there a way to identify and remove spans without ids from a string? I have a text with several spans, some with ids and some without. Input: <span>Hi there!</span><span id="blabla">This is a test</span> Output: Hi there!< ...

What is causing the error when trying to parse a JSON with multiple properties?

Snippet: let data = JSON.parse('{"name":"dibya","company":"wipro"}'); Error Message : An error occurred while trying to parse the JSON data. The console displays "Uncaught SyntaxError: Unexpected end of JSON input" at line 1, character 6. ...

Issue: The function "generateActiveToken" is not recognized as a function

I encountered an issue in my Node.js project and I'm unsure about the root cause of this error. Within the config folder, there is a file named generateToken.js which contains the following code snippet: const jwt = require('jsonwebtoken'); ...

What is the benefit of storing an IIFE in a variable?

When it comes to using IIFE in JavaScript and AngularJS, I have come across two common structures: Structure 1: //IIFE Immediately Invoked Function Expression (function () { }()); However, there is another structure where the IIFE is assigned to a var ...

What is the best way to collect and store data from various sources in an HTML interface to a Google Spreadsheet?

Currently, I have a spreadsheet with a button that is supposed to link to a function in my Google Apps Script called openInputDialog. The goal is for this button to open an HTML UI where users can input text into five fields. This input should then be adde ...

Is there a way to insert json data into a form input field using jQuery?

I am attempting to insert the JSON result into an input as the value. This is the code I am using: $.ajax({ type:"POST", url: '{% url "url_searchTour"%}', data: data1, success: function(jsonAjaxResult){ console.log(J ...

The scrollTop feature fails to function properly following an Axios response

I'm currently facing a challenge with creating a real-time chat feature using Laravel, Vue.js, Pusher, and Echo. The issue arises while implementing the following 3 methods: created() { this.fetchMessages(); this.group = $('#group') ...

Attempting to retrieve the current time using JavaSscript

const currentTime = new Date(); const hours = now.getHours(); Console.log(hours); This block of code is returning an error message... Uncaught ReferenceError: now is not defined Please note that this snippet is written in JavaScript. I attempted to us ...

"Encountering Issues with Angular's Modules and EntryComponents during Lazy Loading

Upon lazy loading an Angular module, I encountered an issue when trying to open my DatesModal that resulted in the following error: No component factory found for DatesModal. Have you included it in @NgModule.entryComponents? The declaration and entryCom ...

Google charts appear only after the second request, not on the initial one

Utilizing Google charts to visually represent company performance data. The Javascript code I have written is as follows: <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> go ...

Sporadic UnhandledPromiseRejectionWarning surfacing while utilizing sinon

Upon inspection, it appears that the objects failApiClient and explicitFailApiClient should be of the same type. When logging them, they seem to have identical outputs: console.log(failApiClient) // { getObjects: [Function: getObjects] } console.log(expli ...

Issue with Custom Tooltip in Mootools 1.2 - Images displaying prematurely before hover action

Encountering an issue with Mootools 1.2 Tips (custom tooltips) We are currently utilizing Joomla with the latest update that includes Mootools 1.2, and I am working with the following JS code: $$('.tipz').each(function(element,index) { ...

The longevity of JQuery features

As I work on setting up an on-click callback for an HTML element to make another node visible, I encountered a surprising realization. The following two statements appeared to be equivalent at first glance: $("#title").click($("#content").toggle); $("#tit ...

Optimal method for organizing individuals into teams using Google Apps Script

There are approximately 200 individuals in this particular department. Our goal is to form groups of 4, with each group consisting of members from different teams based in the same city. Each group must have one driver and three non-drivers, all sharing si ...

Discovering how to create a line break within a text area using the $scope feature in Angular

I'm looking to incorporate a text area for chat input that is resizable. I would like to have some pre-filled texts in it, such as: Hi Jhon, Thanks for contacting us.... I want the text to appear on a new line after the existing content in the textar ...

update the variables based on the changes in the service

I have developed a service in my application to retrieve configuration settings from the database. This service is used to display various configurations across different parts of the app. However, I am encountering an issue where the variables do not upda ...

Looking to adjust the title font size when exporting DataTable to Excel?

Would like to customize the title of an excel file exported from Datatable. I attempted to implement a solution found on a stackoverflow post, but it ended up applying the customization to the entire sheet. $("#datatable").DataTable({ ...