In JavaScript, if , else , and else if statements are used for conditional execution of code blocks based on specified conditions. They allow you to control the flow of your program by executing different code blocks depending on whether certain conditions are true or false. Here's how they work:
The if statement executes a block of code if a specified condition is true.
let hour = new Date().getHours();
if (hour < 12) {
console.log("Good morning!");
}
The else statement executes a block of code if the if condition is false.
let hour = new Date().getHours();
if (hour < 12) {
console.log("Good morning!");
} else {
console.log("Good afternoon!");
}
The else if statement provides an alternative condition to check if the preceding if condition is false. You can have multiple else if blocks.
let hour = new Date().getHours();
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
You can nest if statements within each other to create more complex conditional logic.
let hour = new Date().getHours();
let minute = new Date().getMinutes();
if (hour < 12) {
if (minute < 30) {
console.log("It's before 12:30 PM.");
} else {
console.log("It's after 12:30 PM.");
}
}
JavaScript uses short-circuit evaluation, which means that if the first condition in a series of && (AND) or || (OR) conditions evaluates to false or true, respectively, the subsequent conditions are not evaluated.
let x = 5;
if (x > 0 && x < 10) {
console.log("x is between 0 and 10.");
}
These conditional statements are crucial for controlling the flow of your JavaScript code and executing different blocks of code based on specific conditions. They allow you to create flexible and dynamic programs that respond to various situations.