0

function testNum(a) {
  switch (a) {
    case a > 0:
      alert("positif num");
      break;
    case a < 0:
      alert("num is negative");
      break;
    default:
      alert("num is unknown");
  }
}

testNum(4);

So im trying to do this simple if statement with Swtich methods and smh simply not working the way i want,why its not giving me 'num is positive' , ???

2 Answers2

2

Switch in javascript evaluate an expression and not a number ... The common workaround is to use

 switch(true){

 }

see below :

function testNum(a) {
  switch (true) {
    case a > 0:
      alert("positif num");
      break;
    case a < 0:
      alert("num is negative");
      break;
    default:
      alert("num is unknown");
  }
}

testNum(4);
Seba99
  • 1,197
  • 14
  • 38
0

you can't use condition in case use If or this way

function testNum(a) {
  switch (true) {
    case a > 0:
      alert("positif num");
      break;
    case a < 0:
      alert("num is negative");
      break;
    default:
      alert("num is unknown");
  }
}

testNum(4)
Boutamente abdessamad
  • 523
  • 2
  • 10
  • 30