I have a javascript code that asks a user to input an entry, prints out a list of entries, and deletes. The problem is that when the user inputs delete and than enters an invalid number the code says to enter a correct index but if the user inputs still an incorrect index value based on my specifications the code stops checking whether it passes the test. I need the code to constantly check if the input is valid for index even after the user keeps putting a wrong index number. The code must not exit unless the correct index value is entered. Here is the 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")
Replace this part:
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"))
}
With this -- using a loop:
let index = parseInt(prompt("Enter the index of the todo you would like to delete"));
while (!(index < todo.length && index >= 0)) {
index = parseInt(prompt("Enter a correct index"));
}
todo.splice(index, 1);
tracker = 0;
Note: parseInt will never return null, so no need to check for that. Instead, it could return NaN. But as any comparison with NaN will evaluate to false, the negation of that (using !) will evaluate to true.