Switch case with conditions

A switch works by comparing what is in switch() to every case.

switch (cnt) {
    case 1: ....
    case 2: ....
    case 3: ....
}

works like:

if (cnt === 1) ...
if (cnt === 2) ...
if (cnt === 3) ...

Therefore, you can’t have any logic in the case statements.

switch (cnt) {
    case (cnt >= 10 && cnt <= 20): ...
}

works like

if (cnt === (cnt >= 10 && cnt <= 20)) ...

and that’s just nonsense. 🙂

Use if () { } else if () { } else { } instead.

Leave a Comment