Conditional Statements

Conditional statements are most often used to compare two or more than two value either true or false. conditional statements are used with comparison and logical operators.

there are two types of conditional statements:
1) if...elase statement
2) Switch statement

If Statement
If statement is very famous statement in JavaScript and other programming languages. This statement is used when a condition is true and another condition is false

Syntax
if (condition) statement;
if (condition)
statement
else
statement;
if (condition)
statement
elseif (condition)
statement
else
statement;

Example
<html>
<body>
<script language="javascript">
a=5;
b=10;
if (a<=b)
document.write("Values are not equal!");
else
document.write("Values are equal");
</script>
</body>
</html>

In this code you can see if a variable equal to b then execute "values are not equal" otherwise execute else statement ("values are false"). You can also use other comparison operators as well as you can use if .. else statement with logical operators

<html>
<body>
<script language="javascript">
day1="Sat";
day2="Sun";
if((day1=="Sat")||(day2=="Sub")){
document.write("These are holidays");
}else{
document.write("These are Working days");
}
</script>
</body>
</html>

This example displays multiple if else statements

<html>
<body>
<script language="javascript">
if(operator=="+"){
result = operand1 + operand2;
else if(operator=="-"){
result = operand1 - operand2;
}
else if(operator=="*"){
result = operand1 * operand2;
}
else if(operator=="/"){
result = operand1 / operand2;
}
else
{
document.write("unknown operator");
}
</script>
</body>
</html>

Switch Statement
An if statement can contain as many elseif clauses as you need, but including many of these clauses can often create complex code, alternative is of if elase statement is available. switch is a conditional statement that can have multiple branches in a much more compact format.

switch (expression) {
case constant:
statements;
...
case constant:
statements;
default:
statements;
}

Example

switch (operator) {
case '+': result =operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default:
document.write("unknown operator:");
break;
}

Note: For better understanding, practices if else statement with all comparison and logical operators, then you can better understand.

Bookmark This Page

Link Partners