0

Why does this return the default case:

var score=parseInt(3);
switch(score))
{
 case(score<1):
  alert('DUFF');
  break;
 case(score<5):
  alert('AWESOME');
  break;
 default:
  alert('NOPE');
  break;
}

I've researched it but none of the solutions I've found work.

sanepete
  • 979
  • 9
  • 28
  • I trimmed the code for the sake of brevity. Maybe you shouldn't do this for iterative processes. I actually have dozens of potential scores to test against (not just 1 and 5). The accepted answer on this post [link](http://stackoverflow.com/questions/2312817/javascript-switch-with-logical-operators) suggested boolean operators were possible so this became a 'Why doesn't MY code work' question which I didn't quite see as a duplicate. I am now enlightened. – sanepete Jun 11 '14 at 08:24

3 Answers3

4

Because score having the integer value of 3 will never become boolean true or false, as (score < 1) is false and (score < 5) is true.

switch statement checks if the passed variable (or value) equals to one of the cases, i.e.:

switch (score) {
    case 1:
        // score is 1
        break;
    case 3:
        // score is 3
        break;
    case true:
        // score is true
        break;
    default:
        // neither of above
}

What you are trying to achieve with switch statement can be done as follows:

switch (true) {
    case (score < 1):
        alert('DUFF');
        break;
    case (score < 5):
        alert('AWESOME');
        break;
    default:
        alert('NOPE');
}
VisioN
  • 143,310
  • 32
  • 282
  • 281
0

This is a duplicate of javascript: using a condition in switch case


That being said, it would be better to just use if statements. You can use conditions (not just values) in your case statements, just by removing the parenthesis (see linked SO post above).

When you're not doing pattern matching, ifs are fine:

var score = parseInt(3);
if (score < 1) {
    alert('DUFF');
} else if (score < 5) {
    alert('AWESOME');
} else {
    alert('NOPE');
}
Community
  • 1
  • 1
Ryan Erdmann
  • 1,786
  • 10
  • 11
-1

This code becomes:

var score=3; // No need for parse here
switch(score)
{
 case(false): /*score<1 */
  alert('DUFF');
  break;
 case(true): /* score<5 */
  alert('AWESOME');
  break;
 default:
  alert('NOPE');
  break;
}

You need:

var score= 3;

if (score<1) {
  alert('DUFF');
} else if (score<5) {
  alert('AWESOME');
} else {
  alert('NOPE');
}
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74