Switch statments

hey,

i am trying to run this code but i get nothing in the console, no output and no error:

well without the context it’s difficult to know what you’re expecting, but in any case you are passing “a” to your switch statement, which means that any ‘case’ you use would reference whatever the value of “a” is.

Such that, your “case 1” specifically translates to “if (a === 1)”. So, it would be impossible for your operation “if(a>1)” to ever be true because that operation would only be attempted if “a” were to equal 1, as per your case definition.

hey @fentablar thanks for replying!

I am trying to write a simple code with switch that has 2 cases. the first is a situation when a>1 and the other is default. is there a way to enter if statement inside the switch case?

when i write case 1: it means that this is a case where “a” is equal to 1 ?

Correct. It may behove you to check out MDN’s documentation on switch: switch - JavaScript | MDN

thanks!

so basically i can’t use if statement in a case like this:

case if (a>1):

switch (a) {
   case 1:  { do something } 
 } // end case 

is the equivalent of:

if (a==1) {
   {do something}
} 

If you need to use comparison operators like <=, >=, etc… you need to use an if( ) statement.

You would need to use
case (a>1) :
ann = “delta”;
break;

(At least as far as my knowledge of switch statements goes).

1 Like

No, that doesn’t work… JS will complain of Invalid or unexpected token. Try it in your console.

Now, you can have a comparison in your switch, but your case statements will be true or false

switch (5<4){
    case true: console.log('so true');
        break;
    case false: console.log('nope');
        break;
           }

actually you could do:

switch (true) {
  case a > 1:
    //do something;
    break;
  default:
    //default action;
}

again, refer to MDN – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch#Can_I_use_switch_to_simplify_multiple_if’s

2 Likes

I’ll be dipped… never used that. Thanks for the info!

2 Likes

yeah – when I first read that, I thought to myself “ok, but why would anyone ever actually do that”, but then I thought about the possibilities if you don’t use breaks in the cases and could trigger multiple non-related operations with a single switch

Yeah, it seems counter-intuitive. Like saying

if (true) {
    if (a >1) { 
        // do something
    }
    if (a <1) {
       // do something
    }
}

… might as well do if…then in the first place.

But If one removes the breaks to let it fall down like waterfall, it might have some use case scenario.
But me I think it’s fertile ground for program logic bugs.

Aren’t switch statements used in Ruby?

It seems like you are trying to put an if statement into your switch statement, which is invalid syntax. I created a video on flow control on youtube if you are interested in watching another reference regarding switch cases:

1 Like