What is the best way to verify the accuracy of a value in JavaScript as I move forward?

My JavaScript code prompts the user to input an entry, displays a list of entries, and allows for deletion. However, there is an issue when the user enters "delete" followed by an invalid number. The code asks for a correct index, but if the user continues to input incorrect values, it stops checking altogether. I need the code to continuously validate the index input, even if the user repeatedly enters wrong numbers. It should not exit until the correct index value is provided. Below is the existing code:

let action = prompt("What would you like to do");
const todo = [];
let count=0;
let tracker=0;
let char = 'x';
while (action !== 'quit' && action !== 'q'){
    if (action === 'new'){
        action = prompt("What would you like to add");
        todo.push(action);
        tracker=0;
    }
    else if (action === 'list'){
        console.log(char.repeat(10));
        for (let elements of todo){
            console.log(`${tracker}: ${elements}`);
            tracker++;
        }
        console.log(char.repeat(10));
        action = prompt("What would you like to do");
    }
    else if (action === 'delete'){
        let index = parseInt(prompt("Enter the index of the todo you would like to delete"));
        if (index<todo.length && index >-1 && index!==null){
            todo.splice(index,1);
            tracker=0;
        }
        else{
                let index = parseInt(prompt("Enter a correct index"));
            }
        action = prompt("What would you like to do");
    }
    else
    {
        action = prompt("What would you like to do"); 
    }
}
console.log("Ok quit the app")

Answer №1

Upgrade this section:

let index = parseInt(prompt("Please provide the index of the todo you want to remove"))
if (index < todo.length && index >= 0) {
    todo.splice(index, 1)
    tracker = 0;
}
else {
        let index = parseInt(prompt("Please enter a valid index"))
    }

with this solution -- incorporating a loop:

let index = parseInt(prompt("Please provide the index of the todo you want to remove"));
while (!(index < todo.length && index >= 0)) {
    index = parseInt(prompt("Please enter a valid index"));
}  
todo.splice(index, 1);
tracker = 0;

Note: The function parseInt will not return null, eliminating the need for that check. Instead, it may return NaN. Nonetheless, comparisons with NaN always result in false, so by using the negation operator (!), it evaluates to true.

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

What steps should I take to export a function from a React functional component in order to create a reusable library?

Currently, I am in the midst of developing a React component library and one of my components contains a function that I want to export. The purpose of the addParticle function is to enable users of the library to dynamically insert particles into a cont ...

React component failing to update after receiving response from server for a specific room using socket.io-client with Python backend

I've developed a server backend in Python with Flask-SocketIO that includes a room feature for private conversations. When a user joins a room, the server triggers a function to inform the frontend where to direct messages to a specific user: socketio ...

Issue with displaying Jquery AJAX response in specific div

Having trouble with my JQUERY function. I've got an onclick event triggering a dialog box to open. But upon opening, the dialog box calls two separate jQuery functions. Both functions are supposed to fetch member information based on ID, but only on ...

What could be the reason the server actions in nextjs 13 are not functioning correctly?

I am currently working on a project to retrieve data from mockapi.io, a mock API. However, I am encountering an issue where the fetched data is not displaying in the browser. There are no visible errors, and the browser window remains blank. Interestingly, ...

jinja2.exceptions.UndefinedError: The variable 'asset' has not been defined

Currently in my project, I am using a Python backend to fetch data from an API and then rendering it through Flask to the Vue.js frontend. However, I have encountered an error titled that is causing some issues. I have double-checked and printed the varia ...

Changing a get request to a post request: A step-by-step guide

I have been utilizing the following script: $(document).ready(function() { $("#test-list").sortable({ handle : '.handle', start: function(){ $("#success-result").html("loading...."); }, update : function ( ...

Calculate the total amount from the selected items on the list, depending on the clicked ('active') element

My main objective is to achieve the following: Before any clicks || After the user selects the desired item After conducting some research, I successfully implemented this using vue.js https://jsfiddle.net/Hanstopz/Lcnxtg51/10/ However, I encountered ...

Ways to mimic an Angular directive with a required field

Recently, I encountered a challenge that involves two directives: directive-a, directive-b. The issue arises because directive-b has a `require: '^directive-a' field, which complicates unit testing. In my unit tests, I used to compile the direc ...

Fiber react three selection group

I am attempting to combine/select multiple meshes as a group. Currently, my code looks like this: //wrapper <group onPointerOver={(e) => getOverEvent(e)} onPointerOut={(e) => getOutEvent(e)} onPointer ...

The 'import' statement is not functioning properly within a script in the rendered HTML

While working on an express application, I've encountered a recurring error that I can't seem to solve. The error message is: "GET http://localhost:3000/javascript/module2 net::ERR_ABORTED 404 (Not Found)" Could someone kindly assist me in ident ...

form for submitting multiple data via Ajax

I am working with two forms (request and feedback) where I need to use jQuery Ajax to send the data. When a user submits a request, the subject line will display "Request". If they submit feedback, the subject line will display "Feedback". Here is my cur ...

Combine JavaScript array objects based on their unique IDs

Looking to combine 2 arrays of objects based on IDs (ID and AUTOMOBIL). However, the current code only saves the last array of objects (OPREMA). Any suggestions on how to merge all of them correctly? If the ID in a1 is == 1, I want to save all OPREMA wher ...

Ways to ensure that text wraps to a new line when it exceeds the container's width

I am currently working on implementing a line of text within an ion-card element, but the challenge lies in the fact that the length of the text varies each time. In order to ensure that the entire text is visible and not cut off, especially on devices wit ...

Bigger than 100x100 Soundcloud profile picture size

Is it possible to retrieve a user's image larger than 100x100 using the Soundcloud API? Upon reviewing their documentation, I have not come across any images exceeding this size: An ideal solution would involve some form of Javascript implementation. ...

Tracking your daily nutrition using cronometer with the powerful combination of JavaScript

I'm currently developing a JavaScript cronometer in vueJS. I want the timer to start at 5 minutes (300 seconds) and then continue counting minutes and seconds. Although my cronometer is functioning, I am struggling to get it to start counting minutes ...

Connecting an AngularJS directive to a controller

I'm in the process of learning AngularJS directives and facing a challenge. Here's the JSFiddle link to an example I'm working on: https://jsfiddle.net/7smor9o4/ In the example, my expectation is for the vm.alsoId variable to match the valu ...

Styling text using SVG in HTML

I'm trying to underline a text element in SVG using the text-decoration attribute, but I'm running into an issue with the color of the line not changing. Here is the code snippet I am working with: <svg id="svg" viewBox="0 0 300 ...

Struggling to generate fresh vue components

Having trouble registering new components in my Vue app. I have successfully registered some components, but when I try to register a new one, I encounter the error: Unknown custom element: <store> - did you register the component correctly? For re ...

Working with JSON objects in AngularJS

I have a JSON dataset in the following structure. I need to extract information from the JSON and display it on an HTML table. [region: [name:"", code:""IntradayBalance:{ currency:,Time:,Balance: }.... ], acccountcurrencyBalance:[{ c ...

express-locale: locales property not functioning as intended

I've been experimenting with using express-locale (v1.0.5) as middleware in my express app to identify the locale based on the browser request. My goal is to compare the identified locale with a list of 'allowed' locales and use a default i ...