JavaScript if...ElseStatements
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. 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, and execute 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
if Statement
This statement will only execute code when the specified condition is true.
Syntax
{
Code executed when the condition is true
}
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":
x The result is:
Try it Yourself »
Note that in this syntax, there is no ..else.. You have told the browser to execute code only when the specified condition is true.
if...else Statement
Use the if....else statement to execute code when the condition is true, and execute other code when the condition is false.
Syntax
{
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, generate the greeting "Good day", otherwise generate the greeting "Good evening".
x The result is:
Try it Yourself »
if...else if...else Statement
Use the if....else if...else statement to select one of several code blocks to execute.
Syntax
{
Code executed when condition 1 is true
}
else if (condition2)
{
Code executed when condition 2 is true
}
else
{
Code executed when neither condition 1 nor condition 2 is true
}
Example
If the time is less than 10:00, generate the greeting "Good morning"; if the time is greater than 10:00 and less than 20:00, generate the greeting "Good day"; otherwise generate the greeting "Good evening":
x The result is:
Try it Yourself »
More Examples
Random link
This example demonstrates a link that takes you to different places when you click it. Each chance has a 50% probability.