Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
JavaScript supports the following conditional statements:
- if - execute some code only if a specified condition is true
- if...else - execute some code if the condition is true and another code if the condition is false
- if...else if...else - select one of many blocks of code to be executed
- switch - select one of many blocks of code to be executed
if statement
The if
statement is used to execute some code only if a specified condition is true.
The if
statement has the following syntax:
if (condition)
{
executed if condition is true;
}
The following example shows the basic use of the if
statement.
<script>
//Write a "Good morning" if
//the time is less than 12
var d = new Date();
var hour = d.getHours();
if (hour < 12)
{
document.write("Good morning");
}
</script>
if...else statement
The if...else
statement is used to execute some code only if a specified condition is true and some other code if the condition is false.
The if...else
statement has the following syntax:
if (condition)
{
executed if condition is true;
}
else
{
executed if condition is false;
}
The following example shows the basic use of the if...else
statement.
<script>
//Write a "Good morning" if
//the time is less than 12
//Otherwise, write "Good day"
var d = new Date();
var hour = d.getHours();
if (hour < 12)
{
document.write("Good morning");
}
else
{
document.write("Good day");
}
</script>
if...else if...else statement
The if...else if...else
statement to select one of several blocks of code to be executed.
The if...elseif...else
statement has the following syntax:
if (condition)
{
executed if condition is true;
}
elseif (condition)
{
executed if condition is true;
}
else
{
executed if condition is false;
}
The following example shows the basic use of the if...elseif...else
statement.
<script>
//Write a "Good morning" if
//the time is less than 12
//Write a "Good afternoon" if
//the time is greater than 12
//and less than 18
//Otherwise, write "Good day"
var d = new Date();
var hour = d.getHours();
if (hour < 12)
{
document.write("Good morning");
}
else if (hour > 12 && hour < 18)
{
document.write("Good afternoon");
}
else
{
document.write("Good day");
}
</script>
switch statement
The switch
statement is used to perform different actions based on different conditions.
The switch
statement has the following syntax:
switch (n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
executed if n is not equal to
case 1 or case 2
}
The following example shows the basic use of the switch
statement.
<script>
var d = new Date();
dayOfWeek = d.getDay();
switch (dayOfWeek)
{
case 5:
document.write("TGIF");
break;
case 6:
case 0:
document.write("Party Time");
break;
case 1:
document.write("Back to work");
break;
default:
document.write("Waiting for the weekend");
}
</script>