Wednesday, 23 March 2016

Javascript - If Statement


The JavaScript if statement is used to execute the code whether condition is true or false. There are three forms of if statement in JavaScript.
  1. If Statement
  2. If else statement
  3. if else if statement
1. If statement
Syntax:
if(expression){
//content to be evaluated
}  
As per the syntax the content will only execute if the condition is true.

Example:
<script> 
var a=10;
if(a>5){
document.write("greater than 5");
}
</script>  

Output: greater than 5

2. If else statement
Syntax:
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}  
As per the syntax two sections will execute if the content is true and false respectively

Example:
<script>  
if (count < 10) {
    range= "low";
} else {
     range= "high";
}
</script> 

Output: high

3.JavaScript If...else if statement
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
}  

Example:
<script> 
var a=10;
if(a==5){
document.write("a is equal to 5");
}
else if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else{
document.write("a is not equal to 5,10 or 15");
}
</script>  

Output:a is equal to 10

1 comment :