When it comes to the branching structure in JavaScript, we have to mention the word Process control, and all of our programs are made up of data and algorithms.
program = data + algorithm
Usually we call the algorithm can be done by "order", "branch", "loop" three kinds of structure to complete the combination.
In the ECMA, some statements (also called Process Control statements, branch structure statements) are defined, essentially defining the primary syntax in ECMAScript, which typically uses one or more keywords to accomplish a given task.
1.1 If statement
If statement-use this statement to execute code only if the specified condition is true
1 if (condition) 2 {3 code executed when the condition is true 4 }
If...else Statement-executes code when the condition is true and executes other code when the condition is false
1 if (condition) 2 {3 code executed when the condition is true 4 }5 else6 {7 code executed when the condition is not true 8 }
If...else If....else Statement-Use this statement to select one of several code blocks to execute
1 if (condition 1) 2 {3 code executed when condition 1 is true 4} 5 else if (condition 2) 6 {7 code executed when condition 2 is true 8} 9 Else10 {11 when condition 1 and condition 2 are not Tru e When executing code 12}
1.2 Switch statement
Use the switch statement to select one of several code blocks to execute.
1 switch (n) 2 {3 case 1:4 Execute code block 1 5 Break , 6 case 2:7 Execute code block 2 8 Break , 9 default:10 n with Case 1 and CA SE 2 code executed at different time 11}
How it works: first set an expression n (usually a variable). The value of the subsequent expression is compared to the value of each case in the structure. If there is a match, the code block associated with the case is executed. Use break to prevent your code from automatically running down a case.
Default keyword
Use the default keyword to specify what to do when a match does not exist:
1 var day=new Date (). GetDay (); 2 Switch (Day) 3 {4 case 6:5 x= "Today it's Saturday"; 6 break , 7 case 0:8 x= "Today it ' s Sunday"; 9 break;10 default:11 x= "Looking forward to the Weekend"; 12}
Explanation: Today is not a code snippet that will be executed in Saturday or Sunday.
Comparison of 1.3 if and switch
The switch case vs . If switch case is used only for the conditions that are equal to the comparison if the If (Boolean (conditional)) else if () is available with an implicit conversion, Convert condition to Boolean efficiency slightly lower switch case equals comparison without implicit conversion, slightly higher efficiency
Branching structure in JavaScript