What I'm trying to do is make a user able to enter multiple options from a prompt, and I can't make it so that it doesn't matter if "rcz" is entered with or without capital letters, I always get the same error. I need my counter to appear in the console, but instead I got this:
Uncaught TypeError: Cannot read properties of null (reading 'toLowerCase')
Code I'm using:
alert(`Choose one or more cars. If you want to stop press ESC`);
let userPrompt = prompt(`Available cars: 208, 308, RCZ`);
let promptToLC = userPrompt.toLowerCase();
let counter = 0;
while(userPrompt != null) {
switch(promptToLC) {
default:
alert(`We don't have that car. Try again.`);
break;
case "208":
counter = counter + 1;
break;
case "308":
counter = counter + 1;
break;
case "rcz":
counter = counter + 1;
break;
}
userPrompt = prompt(`Available cars: 208, 308, RCZ`);
promptToLC = userPrompt.toLowerCase();
}
console.log(counter);
This is most likely because there is a chance that 'userPrompt' is null in the case that the user cancels the prompt with no input.
You can assert that the prompt is not null by changing your statement to:
let promptToLC = (userPrompt ? userPrompt:"").toLowerCase();
This conditional statement will ensure that in the case "userPrompt" is null (falsey value by default), the null value will not be used and instead the empty string will be.
prompt(`Available cars: 208, 308, RCZ`);
returns a string or null. userPrompt.toLowerCase(); causes an error if userPrompt is null. You can fix it with conditional chaining operator ?.:
alert(`Choose one or more cars. If you want to stop press ESC`);
let userPrompt = prompt(`Available cars: 208, 308, RCZ`);
let promptToLC = userPrompt?.toLowerCase();
let counter = 0;
while(userPrompt != null) {
switch(promptToLC) {
default:
alert(`We don't have that car. Try again.`);
break;
case "208":
counter = counter + 1;
break;
case "308":
counter = counter + 1;
break;
case "rcz":
counter = counter + 1;
break;
}
userPrompt = prompt(`Available cars: 208, 308, RCZ`);
promptToLC = userPrompt?.toLowerCase();
}
console.log(counter);
or a modified logic without promptToLC:
alert(`Choose one or more cars. If you want to stop press ESC`);
let userPrompt = prompt(`Available cars: 208, 308, RCZ`);
let counter = 0;
while(userPrompt != null) {
// const promptToLC = userPrompt.toLowerCase();
switch(userPrompt.toLowerCase()) {
default:
alert(`We don't have that car. Try again.`);
break;
case "208":
counter = counter + 1;
break;
case "308":
counter = counter + 1;
break;
case "rcz":
counter = counter + 1;
break;
}
userPrompt = prompt(`Available cars: 208, 308, RCZ`);
}
console.log(counter);