The JavaScript if-else 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
JavaScript If statement
The evaluation of the content occurs solely when the expression evaluates to true. Below is the syntax for the JavaScript if statement.
if(expression){
//content to be evaluated
}
Flowchart of JavaScript If statement
Let's examine a straightforward illustration of the if statement in JavaScript.
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
Output of the above example
JavaScript If...else Statement
It assesses the content based on whether the condition is true or false. The syntax for the if-else statement in JavaScript is outlined below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Flowchart of JavaScript If...else statement
Let us examine an instance of an if-else statement in JavaScript that determines whether a number is even or odd.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
Output of the above example
JavaScript If...else if statement
It assesses the content solely when the expression evaluates to true among multiple expressions. The syntax for the JavaScript if-else if statement is provided below.
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
}
Let us examine a straightforward illustration of the if-else if structure in JavaScript.
<script>
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>