Conditional Statements
The conditional statements are used to perform different actions for different decisions.
Just like any other languages, JavaScript has the following conditional statements:
- if for specifying a block of code to be executed, when a specified condition becomes true
- else to specify a block of code to be executed, when the condition is false
- else if (nested if) for specifying a new condition to test, when the first condition becomes false
The if Statement
Use the if statement to specify a block of JavaScript code to be executed when a condition becomes true.
Syntax of if statement
if(condition){
block of code to be executed if the condition becomes true
}
Example
Make a “Good Morning” greeting if the hour is greater than 06:00:
if(hour > 6){
greeting = "Good Morning";
}
The if else Statement
Use of else statement for specifying a block of code to be executed when the condition becomes false.
Syntax of if else statement
if(condition){
block of code to be executed if the condition becomes true
}
else{
block of code to be executed when the condition becomes false
}
Example of if else
If the hour is less than 12, create a “Good Morning” greeting, otherwise “Good Afternoon”:
if(hour < 12){
greeting = "Good Morning";
}
else{
greeting = "Good Afternoon";
}
The else if Statement
Use else if statement to specify a new condition when the first condition is false.
Syntax
if (condition1) {
block of code to be executed if condition1 becomes true
}
else if (condition2) {
block of code to be executed if the condition1 is false and condition2 becomes true
}
else {
block of code to be executed when the condition1 is false and condition2 becomes false
}
Example of else if
If time is less than 12:00, create a "Good morning" greeting, if not, but time is less than 18:00, create a "Good day" greeting, otherwise a "Good evening":
if (time < 12) {
greeting = "Good morning";
}
else if (time < 18) {
greeting = "Good day";
}
else {
greeting = "Good evening";
}