JavaScript Conditional Statement
JavaScript if...else Statement
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 - Only when the specified condition is true, use this statement to execute the codes
if...else statement - Executes codes when the condition is true, executes other codes 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 codes blocks to execute
if Statement
Only when the specified condition is true, the statement will execute the codes.
Grammar
if ( condition )
{
code executed when the condition is true
}
Please use lowercase if . Using capital letters (IF) will generate a JavaScript error!
Example
When the time is less than 20:00, the greeting "Good day" is generated:
if (time<20) { x="Good day"; }
The x result is: Good day
Please note that there is no ...else... in codes. You have told the browser to execute the codes only when the specified condition is true.
if...else Statement
Please use if...else statement to execute codes when the condition is true, and execute other codes when the condition is false.
Grammar
if ( condition )
{
codes is executed when the condition is true
}
else
{codes is 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.
if (time<20) { x="Good day"; } else { x="Good evening"; }
The x result is: Good day
if ... else if ... else Statement
Use if...else if...else statement to select one of multiple code blocks to execute.
Grammar
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 neither 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:
if (time<10) { document.write("<b>Good morning</b>"); } else if (time>=10 && time<20) { document.write("<b>Good today</b>"); } else { document.write("<b>Good evening!</b>"); }
The x result is: Good evening
More Examples
Random link
This example demonstrates a link, when you click on the link, it will take you to different places. Every chance is a 50% probability.