In JavaScript we have following conditional statements -
- if statement
- if…else statement
- if….else if…..else ladder
- switch statement
Why we need conditional statements ?
Conditional statements are used to perform certain action depending on the condition. Depending on the current situation we can decide code flow at run time.
if Statement
if(condition) { statement 1 statement 2 . . . statement 3 statement 4 }
Live Example :
<html> <body> <script type="text/javascript"> var d = new Date(); var time = d.getHours(); if (time < 10) { document.write("<b>Good morning</b>"); } </script> </body> </html>
Explanation :
- Check whether current time is less than 10 or not.
- If time is less than 10 then we are going to print “Good Morning” message.
- If block will never be executed if time is greater than 10.
- if statement is written in lowercase “if”. “IF” will generate JavaScript error.
if….else Statement
if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true }
Live Example :
<html> <body> <script type="text/javascript"> var d = new Date(); var time = d.getHours(); if (time < 10) { document.write("<b>Good morning</b>"); } else { document.write("<b>Have a good day</b>"); } </script> </body> </html>
Explanation :
- if..else statement check condition inside if.
- If condition mentioned inside if statement is true then it will execute “if block“.
- If condition mentioned inside if statement is false then it will follow “else block“.
if…else Ladder
if (condition1) { 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 neither condition1 nor condition2 is true }
Live Example :
<html> <body> <script type="text/javascript"> var d = new Date(); var time = d.getHours(); if (time < 10) { document.write("<b>Good morning</b>"); } else if(time < 16 && time > 10) { document.write("<b>Good Afternoon</b>"); } else { document.write("<b>Have a good day</b>"); } </script> </body> </html>
Explanation :
- Suppose current time is less than 10 then “Good Morning” will be printed.
- If current time is in between 10 and 16 then “Good Afternoon” will be printed.
- If both condition fails then else block is followed.