How to use Conditional Statements in JavaScript

Conditional statements are used to decide the flow of execution based on different conditions. If a condition is true, you can perform one action and if the condition is false, you can perform another action.
Different Types of Conditional Statements
There are mainly three types of conditional statements in JavaScript.
  1. If statement
  2. If…Else statement
  3. If…Else If…Else statement
If statement
Syntax:
?
1
2
3
4
5
6
7
if (condition)
 
{
 
lines of code to be executed if condition is true
 
}
You can use If statement if you want to check only a specific condition.
Try this yourself:
This code is editable. Click Run to Execute
1
2
    <html>
3
4
    <head>
5
6
    <title>IF Statments!!!</title>
7
8
    <script type="text/javascript">
9
10
    var age = prompt("Please enter your age");
11
12
    if(age>=18)
13
14
    document.write("You are an adult <br />");
15
16
    if(age<18)
17
18
    document.write("You are NOT an adult <br />");
19
20
    </script>
21
22
    </head>
23
24
    <body>
25
26
    </body>
27
28
    </html>
29
If…Else statement
Syntax:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if (condition)
 
{
 
lines of code to be executed if the condition is true
 
}
 
else
 
{
 
lines of code to be executed if the condition is false
 
}
You can use If….Else statement if you have to check two conditions and execute different set of codes.
Try this yourself:
This code is editable. Click Run to Execute
1
2
    <html>
3
4
    <head>
5
6
    <title>If...Else Statments!!!</title>
7
8
    <script type="text/javascript">
9
10
    // Get the current hours
11
12
    var hours = new Date().getHours();
13
14
    if(hours<12)
15
16
    document.write("Good Morning!!!<br />");
17
18
    else
19
20
    document.write("Good Afternoon!!!<br />");
21
22
    </script>
23
24
    </head>
25
26
    <body>
27
28
    </body>
29
30
</html>
31
If…Else If…Else statement
Syntax:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
if (condition1)
 
{
 
lines of code to be executed if condition1 is true
 
}
 
else if(condition2)
 
{
 
lines of code to be executed if condition2 is true
 
}
 
else
 
{
 
lines of code to be executed if condition1 is false and condition2 is false
 
}
You can use If….Else If….Else statement if you want to check more than two conditions.
Try this yourself:
This code is editable. Click Run to Execute
1
2
    <html>
3
4
    <head>
5
6
    <script type="text/javascript">
7
8
    var one = prompt("Enter the first number");
9
10
    var two = prompt("Enter the second number");
11
12
    one = parseInt(one);
13
14
    two = parseInt(two);
15
16
    if (one == two)
17
18
    document.write(one + " is equal to " + two + ".");
19
20
    else if (one<two)
21
22
    document.write(one + " is less than " + two + ".");
23
24
    else
25
26
    document.write(one + " is greater than " + two + ".");
27
28
    </script>
29
30
    </head>
31
32
    <body>
33
34
    </body>
35
36
    </html>
37