In JavaScript, the if/else statement is known as what is called a conditional statement. Conditional statements are used to perform different actions based on different conditions.
If Statements
The “if” statement is a statement in coding that is used to instruct a block of JavaScript code to be executed if a condition is true.
Example:
- An if statement would be written in the following format:
if (condition) {
// block of code to be executed if the condition is true
}
- If you were writing a code and wanted a greeting to appear that said “Good morning!” if it was before noon, then you would write your if statement in the following format:
if (hour < 12) {
greeting = “Good morning!”;
}
Else Statements
“Else” statements are used to instruct a block of code to be executed if the condition is false.
Example:
- An else statement would be written in the following format:
if (condition1) {
// block of code to be executed if the condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
- If you were writing a code and wanted a greeting to appear that said “Good morning!” if it was before noon, “Good afternoon!” if it was after noon, but before 5:00PM (17:00), and “Good evening!” if it was after 17:00, then you would write your code in the following format:
if (time < 12) {
greeting = “Good morning!”;
} else if (time < 17) {
greeting = “Good afternoon!”;
} else {
greeting = “Good evening!”;
}
Leave a Reply
You must be logged in to post a comment.