Conditional statements are used to execute different actions based on different conditions.
JavaScript If... Else statement
Conditional statements are used to execute different actions based on different conditions.
Condition Statement
Generally, when writing code, you always need to perform different actions for different decisions. You can use conditional statements in the code to complete the task.
In JavaScript, we can use the following conditional statements:
If statement-this statement is used only when the specified condition is true.
If... else statement-when the condition is true, code is executed. if the condition is false, other code is executed.
If... else statement-use this statement to select one of multiple code blocks for execution
Switch statement-use this statement to select one of multiple code blocks for execution
If statement
The code is executed only when the specified condition is true.
Syntax
If (condition) {code executed when the condition is true}
Use lower case if. Using uppercase letters (IF) will generate JavaScript errors!
Instance
When the time is less than, a greeting "Good day" is generated ":
If (time <20) {x = "Good day ";}
The result of x is:
Good day
Note that in this syntax, there is no... else... You have told the browser that the code is executed only when the specified condition is true.
If... else statement
Use the if... else statement to execute code when the condition is true and other code when the condition is false.
Syntax
If (condition) {code executed when the condition is true} else {code executed when the condition is not true}
Instance
When the time is less than, a greeting "Good day" is generated; otherwise, a greeting "Good evening" is generated ".
if (time<20) { x="Good day"; }else { x="Good evening"; }
The result of x is:
Good day
If... else if... else statement
Use the if... else statement to select one of multiple code blocks for execution.
Syntax
If (condition1) {code executed when condition 1 is true} else if (condition2) {code executed when condition 2 is true} else {code executed when condition 1 and condition 2 are not true}
Instance
If the time is less than, a greeting "Good morning" is generated. If the time is later than and less than, a greeting "Good day" is generated; otherwise, a greeting "Good evening" is generated ":
if (time<10) { x="Good morning"; }else if (time>=10 && time<20) { x="Good day"; }else { x="Good evening"; }
The result of x is:
Good day
The above is the content of the JavaScript If... Else statement in the [JavaScript tutorial]. For more information, see the PHP Chinese website (www.php1.cn )!