JavaScript if...Else Statements
Conditional statements are used to perform different actions based on different conditions.
Conditional statement
When writing code, you often need to perform different actions for different decisions. You can use conditional statements in your code to accomplish this.
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 other code when the condition is false
- if...else if....else Statement- Use this statement to select one of several blocks of code to execute
- switch statement - Use this statement to select one of several blocks of code to execute
if statement
This statement executes code only when the specified condition is true.
Syntax
if (
condition
)
{
Code to be 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":
if
(
time
<
20
)
{
x
=
"Good day
"
;
}
The result of x is:
Try it »
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 other code when it is false.
Syntax
if (
condition
)
{
Code to be executed when the condition is true
}
else
{
Code to be 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".
if
(
time
<
20
)
{
x
=
"Good day
"
;
}
else
{
x
=
"
Good evening
"
;
}
The result of **x ** is:
Try it »
if...else if...else statement
Use the if....else if...else statement to select one of several blocks of code to execute.
Syntax
if (
condition1
)
{
Code to be executed when condition 1 is true
}
else if (
condition2
)
{
Code to be executed when condition 2 is true
}
else
{
Code to be 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 "Good day"; otherwise, generate "Good evening":
if
(
time
<
10
)
{
document.
write
(
"
Good morning
"
)
;
}
else
if
(
time
=
10
&&
time
<
20
)
{
document.
write
(
"
Good day
"
)
;
}
else
{
document
.
write
(
"
Good evening!
"
)
;
}
The result of **x ** is:
Try it »
More examples
Random links
This example demonstrates a link that takes you to different places when you click it. Each possibility has a 50% chance.