Conditional Statements
These Statements are used when a User wants to check many conditions.
We have 3 types of Conditional Statements:
1. If Else If
2. Switch Case
3. Ternary Operator
If else Statement is used when we want the compiler to check each and every condition and execute the answer accordingly.
Syntax:
if (condition)
{
statements;
}
else if (condition)
{
statements;
}
else
{
statements;
}
- <html>
- <head>
- <title></title>
- <script type="text/javascript">
- function conditionalConstruct() {
- var UserInput = Number(document.getElementById("txtUserInput").value);
- if (UserInput == 1) {
- alert("You have Entered " + UserInput);
- }
- else if (UserInput == 2) {
- alert("You have Entered " + UserInput);
- }
- else if (UserInput == 3) {
- alert("You have Entered " + UserInput);
- }
- else {
- alert("Unknown Value");
- }
- }
- </script>
- </head>
- <body>
- <form id="form1">
- <div>
- <h3 style="text-align: center">Using Conditional Statements</h3>
- <table style="border: 1px solid blue; font-family: Verdana">
- <tr>
- <td>Enter a number between 1 and 3:
- </td>
- <td>
- <input id="txtUserInput" type="text" /></td>
- <td>
- <input id="btnSubmit" type="button" value="Submit" onclick="conditionalConstruct();"/></td>
- </tr>
- </table>
- </div>
- </form>
- </body>
- </html>
Switch Case statement is used when we don't want the compiler to check each and every condition, rather we want it to directly jump to the condition which meets the requirement.
Syntax:
switch (condition)
{
case value_to_be_checked:
statements;
break;
case value_to_be_checked:
statements;
break;
default: statements;
break;
}
- <html>
- <head>
- <title></title>
- <script type="text/javascript">
- function conditionalConstruct() {
- var UserInput = Number(document.getElementById("txtUserInput").value);
- switch (UserInput)
- {
- case 1: alert("You have Entered " + UserInput);
- break;
- case 2: alert("You have Entered " + UserInput);
- break;
- case 3: alert("You have Entered " + UserInput);
- break;
- default: alert("Unknown Value");
- break;
- }
- }
- </script>
- </head>
- <body>
- <form id="form1">
- <div>
- <h3 style="text-align: center">Using Conditional Statements</h3>
- <table style="border: 1px solid blue; font-family: Verdana">
- <tr>
- <td>Enter a number between 1 and 3:
- </td>
- <td>
- <input id="txtUserInput" type="text" /></td>
- <td>
- <input id="btnSubmit" type="button" value="Submit" onclick="conditionalConstruct();"/></td>
- </tr>
- </table>
- </div>
- </form>
- </body>
- </html>

Join the conversation! Your thoughts help the community grow.