Hey, I don't understand what the difference between the "if...else" and "switch" statements are? Why would I use one over the other because I can only see the need for the "if...else" statement? I have been to various websites to try and understand it but I really don't get it so am hoping someone on here can help me out on this. Thanks!
It's just a preference thing, like using 'for' loop instead of 'while' loop. Usually, I'd use 'switch' instead of if-else only when both of these are true: - there are more than 3 conditions / cases - for each case there's only 1-2 lines of code.
a switch statement is very useful if you're evaluating a single field for multiple different values. consider the following code: var variable = 10; switch (variable){ case 1: //do something break; case 2: //do something break; case 3: //do something break; case 4: //do something break; case 5: //do something break; case 6: //do something break; case 7: //do something break; case 8: //do something break; case 9: //do something break; case 10: //do something break; default: //do something break; } Code (markup): now consider how much extra code you would have to write to write that same thing using nested if/else ifs. if(variable == 1){ //do something }else if(variable == 2){ //do something }else if(variable == 3){ //do something }else if(variable == 4){ //do something }else if(variable == 5){ //do something }else if(variable == 6){ //do something }else if(variable == 7){ //do something }else if(variable == 8){ //do something }else if(variable == 9){ //do something }else if(variable == 10){ //do something }else { //do something } Code (markup): if you have a situation like this a switch is quicker and cleaner to write.
switch Statement Description Enables the execution of one or more statements when a specified expression's value matches a label. Syntax Remarks Use the default clause to provide a statement to be executed if none of the label values matches expression. It can appear anywhere within the switch code block. Zero or more label blocks may be specified. If no label matches the value of expression, and a default case is not supplied, no statements are executed. Execution flows through a switch statement as follows: Evaluate expression and look at label in order until a match is found. If a label value equals expression, execute its accompanying statementlist. Continue execution until a break statement is encountered, or the switch statement ends. This means that multiple label blocks are executed if a break statement is not used. If no label equals expression, go to the default case. If there is no default case, go to last step. Continue execution at the statement following the end of the switch code block. The following example tests an object for its type: