Hi, I’m new to JavaScript and I had a question about the switch statement. The user is prompted to enter their age. Age is saved in the variable senior. If they are older than 54 then they receive an alert prompting them to request the health package.
I wrote the following code and I don’t receive any output. Can I evaluate a statement and then use boolean values of true and false in the case statement?
switch (senior > 54) {
case true:
alert("You are eligible a special health package!");
location.href="website/healthpack";
break;
case false:
location.href="website/shop";
break;
default:
location.href="website home page";
Welcome, @MWms, I have formatted your code for you to make it easier for us to read. In the future, when you post code here you can format it yourself by placing three backticks(```) on the line before the code, and three backticks on the line after the code. Alternatively, you can highlight your pasted code and select the <\> icon from the top of the edit area of your post.
Yes, the switch statement correctly uses the condition and values.
One reason why the code doesn’t output is that you may have forgotten to close off the curly brackets from the start of the switch statement. The closing curly brackets go on a separate line after the last statement in the default section.
For the sake of safety and good practice, it’s better to have the default there anyway to cater for future changes to the switch statement. At least have it fall through, and comment about it to help prevent questions why.
case false:
// fall through to default
default:
location.href="website/shop";