Ben
Ben

Reputation: 3025

Is it valid JavaScript to nest an if/else in a switch?

Is this valid?

switch(foo) {
    case 'bar':
    if(raz == 'something') {
        // execute
    } else {
        // do something else
    }
    break;
    ...
    default:
    // yada yada
}

Upvotes: 24

Views: 52284

Answers (3)

samo0ha
samo0ha

Reputation: 3796

and you can also use ternary if wrapped inside a return statement

   switch(foo) {
        case 'bar':
          return(
            (raz == 'something') ? 
              // excute
            : 
              // do something else
          )
        break;
        ...
        default:
        // yada yada
    }

Upvotes: 1

Jeffrey Roosendaal
Jeffrey Roosendaal

Reputation: 7157

You can combine a switch and an if in a better way, if you really have to:

switch (true) {
    case (foo === 'bar' && raz === 'something'):
        // execute
        break;
    case (foo === 'bar'):
        // do something else
        break;
    default:
        // yada yada
}

Sorry to revive such an old post, but it may help people who came here looking how to combine or nest a switch and an if statement.

Upvotes: 15

karim79
karim79

Reputation: 342665

Yes, it is perfectly valid. Have you tried it?

Upvotes: 27

Related Questions