JavaScript If ... Else statement
For conditional statements based on different criteria to perform different actions.
Conditional statements
Usually when writing code, you always need a different decision to perform different actions. You can accomplish this task using conditional statements in the code.
In JavaScript, we can use the following conditional statement:
- if statement - only if a specified condition is true, use this statement to execute code
- if ... else statement - When the condition is true execute code when the condition is false execute other code
- if ... else if .... else statement - use this statement to select one of a plurality of blocks of code to execute
- switch statement - use this statement to select one of a plurality of blocks of code to execute
If statements
Only when the specified condition is true, the statement will not execute code.
grammar
{
当条件为 true 时执行的代码
}
Please use lowercase if. Uppercase letters (IF) will generate a JavaScript error!
Examples
When the time is less than 20:00, the generated greeting "Good day":
{
x="Good day";
}
x The result:
try it"
Note that in this grammar, no ..else ... You have to tell the browser to execute code only when a specified condition is only true.
If ... else statement
Please use the if .... else statement to execute code if the condition is true, the condition is false execute other code.
grammar
{
When the code is executed if the condition is true
}
else
{
Code is executed when the condition is not true
}
Examples
When the time is less than 20:00, generated greeting "Good day", otherwise generate greeting "Good evening".
{
x="Good day";
}
else
{
x="Good evening";
}
x The result:
try it"
If ... else if ... else statement
Use if .... else if ... else statement to select one of a plurality of blocks of code to execute.
grammar
{
当条件 1 为 true 时执行的代码
}
else if (condition2)
{
当条件 2 为 true 时执行的代码
}
else
{
当条件 1 和 条件 2 都不为 true 时执行的代码
}
Examples
If the time is less than 10:00, the generated greeting "Good morning", if the time is greater than 20:00 and less than 10:00, the generated greeting "Good day", otherwise generate greeting "Good evening":
{
x="Good morning";
}
else if (time>=10 && time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
x The result:
try it"
More examples
Random Links
This example demonstrates a link, when you click on the link, will take you to a different place. Each opportunity is a 50% probability.