JavaScript conditional statements
Conditional statements are used to perform different actions based on different conditions.
Conditional statements
Usually when writing code, you always need to perform different actions for different decisions action. 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 when the specified condition is true
if...else statement - execute code when the condition is true, execute other code when the condition is false
if...else if. ...else statement - Use this statement to select one of multiple code blocks to execute
switch statement - Use this statement to select one of multiple code blocks to execute
If statement
This statement will execute the code only if the specified condition is true.
Syntax
if (condition)
{
Code executed when the condition is true
}
Note: Please use lowercase if. Using uppercase letters (IF) will generate a JavaScript error!
Example
When the time is less than 20:00, generate the greeting "Good day":
php中文网(php.cn) 如果时间早于 20:00,会获得问候 "Good day"。
Note, in this syntax, there is no ..else... You've told the browser to only execute the code if the specified condition is true.
Run the program and try it
If...else statement
Please use if... The .else statement executes 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
}
Example
When the time is less than 20:00, the greeting "Good day" is generated, otherwise the greeting "Good evening" is generated.Run the program and try itphp中文网(php.cn) 点击这个按钮,获得基于时间的问候。
If...else if...else statement
Use if....else if...else statement to select one of multiple blocks of code to execute.Syntax
if (condition1){
Code executed when condition 1 is true
}
else if (condition2)
{
Code executed when condition 2 is true
}
else
{
When neither condition 1 nor condition 2 is true Code executed when true
}
Example
If the time is less than 10:00, the greeting "Good morning" is generated ", if the time is greater than 10:00 and less than 20:00, the greeting "Good day" is generated, otherwise the greeting "Good evening" is generated:Run the program and try itphp中文网(php.cn) 这个例子演示了 if..else if...else 语句。