Neta Meta
Neta Meta

Reputation: 4047

using an if statement or function as a switch case

is it possible to do an if statement in a switch case? or using $.isNumeric funciton ?

I've tried several goes in jsfiddle and it didnt seem to work.

var someVar  = 1;
switch(someVar){
    case someVar < 0:
        console.log('asdasd');
        break;        
}

this didnt seem to work, is ther another way?

http://jsfiddle.net/RLxpU/

Upvotes: 0

Views: 101

Answers (3)

adeneo
adeneo

Reputation: 318302

Nope, you can't use a condition as a case, as it evaluates to a boolean, which doesn't match the switch, try this to see

var someVar  = 1;
switch(false){
    case someVar < 0: // false, someVar is not less than zero
        console.log('asdasd');
        break;        
}

switch(true){
    case someVar > 0: // now it's true, someVar is more than zero
        console.log('asdasd');
        break;        
}

FIDDLE

Upvotes: 3

james emanon
james emanon

Reputation: 11807

In addition to what the others have shown, you can also pass the expression.

var someVar  = -1;
switch(someVar < 0){
  case true:
    console.log('true');
    break;    
  case false:
    console.log('false');
    break; 
  }

Upvotes: 0

Brian North
Brian North

Reputation: 1398

Switch is certainly capable of evaluating expressions and conditions: you just have to pass switch the right thing to evaluate:

switch ( true ) {

    case someVar < 0:
        console.log('asdasd');
        break;

}

Will work since the expression someVar < 0 evaluates to true == the value switch is looking for.

Upvotes: 2

Related Questions