ukri
ukri

Reputation: 277

How to use switch statement inside for loop?

for(var i=0; i<20; i++) {
  if(i%3===0) {
   console.log(i, 'Foo')
  } else {
   console.log(i, 'Default')
  }
}

Now, I wonder how can we write the code using switch statement inside the loop:

for(var i=0; i<20; i++) {
  switch(i) {
   case (i%3===0):
    console.log(i,'Foo')
    break
   default:
    console.log(i,'Default')
    break
  }
}

But it results 'Default' always. I have tried using label, anonymous function, etc. but not able to output like if condition. Am I doing something wrong with the switch statment?

Edit:

I was trying to do like this in fact:

case (i%3===0):
   console.log(i,'Foo')
   break
case (i%5===0):
   console.log(i,'Bar')
   break

Upvotes: 8

Views: 22703

Answers (4)

Unmitigated
Unmitigated

Reputation: 89517

You are trying to use a switch statement like a series of if and else if statements. A switch statement does not work that way. The first case that matches the value of the variable that is in the switch statement will be evaluated. You can use switch(true) so the first case that is true will be evaluated.

for(var i=0; i<20; i++) {
  switch(true) {
   case (i%3===0)://if
    console.log(i,'Foo')
    break
   case (i%5===0)://else if
     console.log(i,'Bar')
     break
   default://else
    console.log(i,'Default')
    break
  }
}

Otherwise, you need to switch the value of i modulo 3 (if it equals zero then it is divisible by 3).

for(var i=0; i<20; i++) {
  switch(i%3) {
   case (0):
    console.log(i,'Foo')
    break
   default:
    console.log(i,'Default')
    break
  }
}

However, a switch statement generally should not be used in this case. You should just go with a series of if (and else if statements).

for(var i=0; i<20; i++) {
  if(i%3==0){
    console.log(i, 'Foo');
  } else if(i%5==0){
    console.log(i, 'Bar');
  } else {
    console.log(i, 'Default');
  }
}

Upvotes: 9

David White
David White

Reputation: 656

try this - with the %3 moved

for(var i=0; i<20; i++) {
  switch(i%3) {
   case 0:
    console.log(i,'Foo')
    break;
   default:
    console.log(i,'Default')
    break;
  }
}

Upvotes: 1

Luca Kiebel
Luca Kiebel

Reputation: 10096

You should switch the expression you want to check against, in this case that's i%3 and than make cases for what that expression might be, e.g. case 0:, case 1: and so on:

for(var i=0; i<20; i++) {
  switch(i%3) {
   case 0:
    console.log(i,'Foo')
    break;
   case 1:
    console.log(i,'Bar')
   default:
    console.log(i,'Default')
  }
}

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30729

You can take the value of i%3 in a variable and use that in switch-case because the case evaluates a constant or expression.

for(var i=0; i<20; i++) {
  var val = i%3;
  switch(val) {
   case 0:
    console.log(i,'Foo')
    break;
   default:
    console.log(i,'Default')
  }
}

Upvotes: 1

Related Questions