JavaScript If-else

In JavaScript Condition statement (if-else) are used to execute a programm with the coditions which may be true or false. There are three forms of if statement in JavaScript.
1- If Statement
2- If else statement
3- if else if statement
4- switch statement

Example of If statement

In this example if statement is used. It evaluates the content only if expression is true.

Syntax
if(expression){
//content to be evaluated
}

<script type = "text/javascript">
var a=20;  
if(a>10){  
document.write("value of a is greater than 10");  
}   
</script>                  
        

Output of above code


Example of If...else Statement

In this example if...else statement is used. It evaluates the content whether condition is true of false.

Syntax
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

<script type = "text/javascript">
var a=20;  
if(a%2==0){  
document.write("a is even number");  
}  
else{  
document.write("a is odd number");  
}    
</script>                  
        

Output of above code


Example of If...else if statement

In this example if... else...if..... statement is used. It evaluates the content only if expression is true from several expressions.

Syntax
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}

<script type = "text/javascript">
var a=20;  
if(a==10){  
document.write("a is equal to 10");  
}  
else if(a==15){  
document.write("a is equal to 15");  
}  
else if(a==20){  
document.write("a is equal to 20");  
}  
else{  
document.write("a is not equal to 10, 15 or 20");  
}     
</script>                  
        

Output of above code


Note:

Switch statement is in next chapter.








The Best

Comment here

If you have any query, if you want to know something about any of technical course related to computer science field, if you have any suggestion about relevant to uploaded content or if you anything wrong here (any mistake in content) than please contact us. Keep in mind, comment should be according to community guidelines.