-2

it shows the default code only what's wrong with this code? I am a beginner programmer. Thank you!

   let age=30;
    switch (age){
        case age > 23:
        console.log("you are allowed to drink beer");
        break;
        case age < 23:
        console.log("you are not allowed to drink or smoke");
        break;
        case age >= 23:
        console.log("you can smoke or drink from next year");
        break;
        default:
        console.log("check your age first in the birth certificate");
    }

1 Answers1

0

That's not how switch/case works. It's a jump table that works for equality only.

Like:

switch (age)
{

What is "age"?

   case 23:

If it's equal to 23...

        console.log("you are allowed to drink beer");
        break;

Or

   case 24:

If it's equal to 24...

        console.log("you are still allowed to drink beer");
        break;

and so on.

}

You're providing more complex expressions, all of which boil down to true/false which is then made into 1/0 for the comparison. Your age is (presumably) never either of those two values, so only the default case ever fires.

For ranges like you've got, you should use an if statement instead:

let age=30;
if (age > 23)
    console.log("you are allowed to drink beer");
else if (age < 23)
    console.log("you are not allowed to drink or smoke");
else
    console.log("you can smoke or drink from next year");

Notice how I changed the age >= 23 case into an else, because it can only be actually equal to 23 at this point and there are no other options. Therefore, also, there is no need for a "default" case.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35