How to Write Conditional Statements in JavaScript?

The different types of conditional statements used in JavaScript for making different decisions are as follows.

If Statement


This statement is used to execute some code only if a specified condition is true.

Syntax:

if {condition}
{
code to be executed if condition is true
}

Example:


This script writes "Good morning" greeting if the time is less than 10

If .... elese statement


This statement is used to execute some code only if the condition is true and another code if the condition is false.

Syntax:

if {condition}
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

Example:



Preview:



If .... else If ..... else statement


This statement is used to select one of many blocks of code to be executed.

Syntax:

if {condition}
{
code to be executed if condition1 is true
}
else if {condition2}
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and condition2 are not true.
}

Example:



Preview:



Switch statement


This statement is used to select one of many blocks of code to be executed.

Syntax:

switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}

Example:

Preview: