
JavaScript Conditional Statements
Conditional statements are used to perform different actions based on different conditions. When you write a code if you want to perform different actions for different decisions. Then you can use conditional statements in your code to do this.
In JavaScript, we have the following conditional statements.
1. if: This conditional statement is used to specify a block of code to be executed if a specified condition is true.
2. else: This conditional statement is used to specify a block of code to be executed if the same condition is false.
3. else if: This conditional statement is used to specify a new condition to test if the first condition is false.
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax
if(condition){
//code to be executed
}
if (hour < 18){ greeting="Good Morning"; } //Output is Good Morning
The else Statement
Use the else statement to specify a block of JavaScript code to be executed if a condition is false.
Syntax
if(condition){
//code to be executed, if the condition is true
}else{
//code to be executed, if the condition is false
}
if (hour < 18){ greeting="Good Morning"; }else{ greeting="Good Evening"; //Output is Good Morning
The else if Statement
Use the else if statement to specify a new condition to test if the first condition is false.
Syntax
if(condition1){
//code to be executed, if the condition1 is true
}else if(condition2){
//code to be executed, if the condition1 is false and condition2 is true
}
else{
//code to be executed, if the condition1 is false and condition2 is false
}
if (time< 10){ greeting="Good Morning"; }else if(time<20){ greeting="Good Day"; }else{ greeting="Good Evening";}