1.JavaScript If ... Else Statement
Conditional statements are used to perform different actions based on different conditions.
1.1 Conditional statements
Often when writing code, you always need to perform different actions for different decisions. You can use conditional statements in your code to accomplish this task.
In JavaScript, we can use the following conditional statements:
- If statement -Use this statement to execute code only if the specified condition is true
- If...else Statement -executes code when the condition is true and executes other code when the condition is false
- if...else if....else Statement -Use this statement to select one of several code blocks to execute
- switch Statement -Use this statement to select one of several code blocks to execute
1.1.1If statements
The statement executes code only if the specified condition is true.
if (condition) { true when executing code}
Please use the lowercase if. Using uppercase letters (IF) generates JAVASCRIPT errors!
1.1.2if...else statements
Use the If....else statement to execute code when the condition is true, and to execute additional code when the condition is false.
if (condition) { true when executing code}Else{ true Code to execute at time}
1.1.3if...else if...else Statements
Use the If....else if...else statement to select one of several code blocks to execute.
if (condition1) { 1true when executing code}Elseif (condition2) { 2 true code to execute at time} Else { 12true when executing code}
2.JavaScript switch Statement
The switch statement is used to perform different actions based on different conditions.
2.1 JavaScript Switch statement
Use the switch statement to select one of several code blocks to execute.
Switch (n) { case1: 1break ; Case 2 : 2 Break ; default : Case 1 Case 2 code executed at different time}
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.
varD=NewDate (). GetDay ();Switch(d) { Case 0: x="today is Sunday"; Break; Case 1: x="today is Monday"; Break; Case 2: x="today is Tuesday"; Break; Case 3: x="today is Wednesday"; Break; Case 4: x="today is Thursday"; Break; Case 5: x="today is Friday"; Break; Case 6: x="today is Saturday"; Break; }
2.1default keywords
Use the default keyword to specify what to do when a match does not exist:
varD=NewDate (). GetDay ();Switch(d) { Case 6: x="today is Saturday"; Break; Case 0: x="today is Sunday"; Break; default: x="looking forward to weekends";} document.getElementById ("Demo"). Innerhtml=x;
JavaScript conditional statements