JavaScript Conditional Statements - IF, Else, Else IF (Example)
JavaScript Conditional Statements - IF, Else, Else IF (Example)
1. If statement
2. If…Else statement
3. If…Else If…Else statement
If statement
Syntax:
if (condition)
You can use If statement if you want to check only a specific condition.
1 <html>
2 <head>
3 <title>IF Statments!!!</title>
4 <script type="text/javascript">
5 var age = prompt("Please enter your age");
6 if(age>=18)
7 document.write("You are an adult <br />");
8 if(age<18)
9 document.write("You are NOT an adult <br />");
10 </script>
11 </head>
12 <body>
13 </body>
14 </html>
Run
If…Else statement
Syntax:
https://www.guru99.com/how-to-use-conditional-statements-in-javascript.html 2/4
7/24/2021 JavaScript Conditional Statements: IF, Else, Else IF (Example)
if (condition)
else
You can use If….Else statement if you have to check two conditions and execute a
different set of codes.
1 <html>
2 <head>
3 <title>If...Else Statments!!!</title>
4 <script type="text/javascript">
5 // Get the current hours
6 var hours = new Date().getHours();
7 if(hours<12)
8 document.write("Good Morning!!!<br />");
9 else
10 document.write("Good Afternoon!!!<br />");
11 </script>
12 </head>
13 <body>
14 </body>
15 </html>
Run
https://www.guru99.com/how-to-use-conditional-statements-in-javascript.html 3/4
7/24/2021 JavaScript Conditional Statements: IF, Else, Else IF (Example)
if (condition1)
else if(condition2)
else
You can use If….Else If….Else statement if you want to check more than two conditions.
1 <html>
2 <head>
3 <script type="text/javascript">
4 var one = prompt("Enter the first number");
5 var two = prompt("Enter the second number");
6 one = parseInt(one);
7 two = parseInt(two);
8 if (one == two)
9 document.write(one + " is equal to " + two + ".");
10 else if (one<two)
11 document.write(one + " is less than " + two + ".");
12 else
13 document.write(one + " is greater than " + two + ".");
14 </script>
15 </head>
16 <body>
17 </body>
18 </html>
Run
https://www.guru99.com/how-to-use-conditional-statements-in-javascript.html 4/4