This particular code snippet is designed to loop indefinitely until the user enters the correct answer in a prompt. The acceptable answers are "left" and "right". If the user inputs any other text, the function promptDirection will throw an error and execute the catch block, prompting the for loop to restart.
One thing that perplexes me about this code is why errors like "Not a valid direction. Try again." are not showing up in the console log each time the catch block runs. These errors only appear once the user provides the correct answer or clicks cancel in the prompt, resulting in a return of "null" which ends the program.
Can anyone shed some light on this behavior?
I would anticipate seeing an error displayed in the console every time the user inputs something other than "left" or "right" into the prompt. However, in practice, if the user enters three incorrect answers, the errors only show up after the program finishes running, displaying three instances of "Not a valid direction. Try again." along with "You chose L" or "You chose R."
For example, inputting into the prompt:
Wrong
Wrong
Wrong
Left
The console does not show any indication of the catch block being triggered three times by InputErrors ("Not a valid direction") until the correct answer is entered. All accumulated errors become visible in the browser console once the program concludes and the correct Left answer is provided.
class InputError extends Error { }
function promptDirection(question) {
let result = prompt(question);
if (result.toLowerCase() == "left") return "L";
if (result.toLowerCase() == "right") return "R";
throw new InputError("Invalid direction: " + result);
}
for (;;) {
try {
let dir = promptDirection("Where?");
console.log("You chose ", dir);
break;
} catch (e) {
if (e instanceof InputError) {
console.log("Not a valid direction. Try again.");
} else {
throw e;
}
}
}