JavaScript if...else Statements
While writing a program, there may be a situation when you need to adopt one path out of the given two paths. So you need to make use of conditional statements that allow your program to make correct decisions and perform right actions.JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain if..else statement.
JavaScript supports following forms of if..else statement:
- if statement
- if...else statement
- if...else if... statement.
if statement:
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.Syntax:
if (expression){
Statement(s) to be executed if expression is true
}
|
Example:
<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
|
Qualifies for driving
|
if...else statement:
The if...else statement is the next form of control statement that allows JavaScript to execute statements in more controlled way.Syntax:
if (expression){
Statement(s) to be executed if expression is true
}else{
Statement(s) to be executed if expression is false
}
|
Example:
<script type="text/javascript">
<!--
var age = 15;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}else{
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
|
Does not qualify for driving
|
if...else if... statement:
The if...else if... statement is the one level advance form of control statement that allows JavaScript to make correct decision out of several conditions.Syntax:
if (expression 1){
Statement(s) to be executed if expression 1 is true
}else if (expression 2){
Statement(s) to be executed if expression 2 is true
}else if (expression 3){
Statement(s) to be executed if expression 3 is true
}else{
Statement(s) to be executed if no expression is true
}
|
Example:
<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
}else if( book == "maths" ){
document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
document.write("<b>Economics Book</b>");
}else{
document.write("<b>Unknown Book</b>");
}
//-->
</script>
|
Maths Book