David G
David G

Reputation: 96790

Why does this switch statement fail?

switch (t.value) {
    case < 5:
        alert('hi');
        break;
}

I know it's the part where I have "< 5". How do I make it so that it has a case where t.value is less than 5??

Upvotes: 0

Views: 131

Answers (4)

nnnnnn
nnnnnn

Reputation: 150010

An if statement seems best suited for this purpose, but although I do not recommend it the fact that JavaScript will let you switch on any datatype (and not just numbers/enums like some languages) means you can do this:

switch(true) {
   case t.value < 5:
      // do something
      break;
   case t.value >= 112:
      // do something
      break;
   case someOtherVar == 17:
      // do something
      break;
   case x == 7:
   case y == "something":
   case z == -12:
   case a == b * c:
      // works with fallthrough
      break;
   case someFunc():
      // even works on a function call (someFunc() should return true/false)
      break;
   default:
      // whatever
      break;
}

The above should select whichever case matches first, noting that several if not all of the cases could be true.

In a way that style is more readable than a long series of if/else if, but I wouldn't use it in a team development environment where it could confuse other developers.

Another, more conventional use of switch for your less than 5 scenario would be as follows (assuming you know the range that t.value could possibly be):

switch(t.value) {
   case 0:
   case 1:
   case 2:
   case 3:
   case 4:
      // do something
      break;
   case 5:
   // etc
}

Upvotes: 3

Jacob Eggers
Jacob Eggers

Reputation: 9322

switch only supports equality comparisons.

if (t.value < 5) {
    alert('hi');
}

I don't know if it fits your particular case, but you could also do something like this:

switch (t.value) {
    case 5:
    case 4:
    case 3:
    case 2:
    case 1:
        alert('hi');
        break;
}

Upvotes: 4

Thinker
Thinker

Reputation: 32

default: if(t.value< 5) alert('hi');
break; Maybe it's you want!

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 992717

switch statements don't support less-than or greater-than comparisons (or anything other than equals). Use:

if (t.value < 5) {
    alert("hi");
}

Upvotes: 2

Related Questions