Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Is this valid?

switch(foo) {     case 'bar':     if(raz == 'something') {         // execute     } else {         // do something else     }     break;     ...     default:     // yada yada } 
like image 401
Ben Avatar asked Feb 07 '11 21:02

Ben


People also ask

Can we use if else in switch?

An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object. Technically, the final break is not required because flow falls out of the switch statement.

Can you use else if in JavaScript?

The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.

Can Switch case have multiple conditions JavaScript?

The JavaScript switch case is a multiple if else statement. It takes a conditional expression just like an if statement but can have many conditions—or cases—that can match the result of the expression to run different blocks of code.

Is switch faster than if else JavaScript?

A switch statement works much faster than an equivalent if-else ladder. It's because the compiler generates a jump table for a switch during compilation. As a result, during execution, instead of checking which case is satisfied, it only decides which case has to be executed.


2 Answers

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

like image 157
karim79 Avatar answered Oct 13 '22 02:10

karim79


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.

like image 45
Jeffrey Roosendaal Avatar answered Oct 13 '22 00:10

Jeffrey Roosendaal