for(var i=0; i<20; i++) {
if(i%3===0) {
console.log(i, 'Foo')
} else {
console.log(i, 'Default')
}
}
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
Share
Improve this question
edited Aug 14, 2018 at 16:56
ukri
asked Aug 14, 2018 at 16:50
ukriukri
2772 gold badges3 silver badges9 bronze badges
3
|
4 Answers
Reset to default 9You 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');
}
}
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')
}
}
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;
}
}
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')
}
}
i%3
in the wrong place. – Pointy Commented Aug 14, 2018 at 16:52switch
statement is not appropriate in that situation. – Pointy Commented Aug 14, 2018 at 16:59