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.
- If Statement
- If else statement
- if else if statement
1. If statement
Syntax:
if(expression){
//content to be evaluated
}
//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>
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
}
//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";
}
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
}
//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>
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
No comments :
Post a Comment