We can use this statement if we want to execute a set of code in case the given condition is true and other code in case of given condition is false. For example: |
if today is Sunday
go to market else go to office |
syntax (How to write): |
if (condition)
{ job to be done if condition is found true } else { job to be done if condition is found false } |
Example |
<html>
<head> </head> <body> <script type=”text/javascript”> var a,b; a=parseInt(prompt(“Enter value for a”,””)) b=parseInt(prompt(“Enter value for b”,””)) document.write(“<br>Value of a “+a); document.write(“<br>Value of b “+b); if (a>b) { document.write(“<br>value of a is greater than b “); } else { document.write(“<br>value of a lesser than or equal to b “); } </script> </body> </html> |
Understanding program : |
In the above program we have used prompt method which is used to accept input from user , we learnt this in dialog box section, parseInt function will convert the accepted value to number type because the value returned by the prompt method will be of string type and we can not compare or perform any arithmetic calculation with a string value, so we used parseInt method. |
Output: |
Value of a 25 Value of b 45 value of a lesser than or equal to b |
Explanation |
If the value of a is entered greater than value of b then the above output will be shown else the below output will be shown. |
Value of a 50 Value of b 20 value of a is greater than b |