I am writing code to learn defensive error handling in javascript. The program calculates distance, time or speed depending on the user's choice. This bit works fine.
I then tried to add a try catch statement under the prompt-time function and this worked. So I took that code and tried making it into one function rather than typing it out thrice. The idea is that if the user enters something that is not a number or blank the program will keep asking for a number until they do.
But now whenever I enter something that is not a number the while loop does not show the prompt and loops indefinitely. I need a while loop as using an if statement makes the program go on without the correct output.
I am not sure why this is happening.
ask = prompt('Calculate distance(d), time (t) or speed (s)')
function notNumber(input) {
while (true)
try {
let input = Number(prompt('Enter your ' + input))
if (isNaN(input) == true || input == "") {
throw "Invalid Input";
}
return input;
}
catch (err) {
console.log(err);
}
}
function promptTime(time) {
time = Number(prompt('Enter your Time'))
if (isNaN(time)) {
notNumber(time)
}
return time;
}
function promptSpeed(speed) {
speed = Number(prompt('Enter your Speed'))
if (isNaN(speed)) {
notNumber(speed)
}
return speed;
}
function promptDistance(distance) {
distance = Number(prompt('Enter your distance'))
if (isNaN(distance)) {
notNumber(distance)
}
return distance;
}
if (ask == 'd') {
let time = promptTime()
let speed = promptSpeed()
distance = time * speed
if (distance == Number) {
console.log('Your distance is ' + distance)
}
if(isNaN(distance)) {
notNumber(distance)
}
}
else if (ask == 't') {
let distance = promptDistance()
let speed = promptSpeed()
time = distance / speed
console.log('Your time is ' + time)
if(isNaN(time)) {
notNumber(time)
}
}
else if (ask == 's') {
let distance = promptDistance()
let time = promptTime()
speed = distance / time
console.log('Your speed is ' + speed)
if(isNaN(speed)) {
notNumber(speed)
}
}
else {
console.log('Please enter a measurement!')
}
Changes: Redefined the promptNumber function from 'input' to a different name ('variable')
Added refer variable to get the name of the desired calculation (time, speed or distance)
Note that I tried calling 'refer' 'name'. But name came up as deprecated.
Got rid of the nested if statements as they are now redundant. For example:
The finalised code is: