What is conditional statement?
Conditional statements in JavaScript allow you to execute different blocks of code based on whether a certain condition is true or false. Here's a breakdown of the common types:
1. if Statement:
Executes a block of code only if the specified condition is true.
let x = 10;
if (x > 5) {
console.log("x is greater than 5");
}
2. if...else Statement:
Executes one block of code if the condition is true, and another block of code if the condition is false.
let y = 3;
if (y > 5) {
console.log("y is greater than 5");
} else {
console.log("y is not greater than 5");
}
3. if...else if...else Statement:
Allows you to check multiple conditions in sequence. If one condition is true, its associated block is executed, and the rest are skipped.
let z = 7;
if (z > 10) {
console.log("z is greater than 10");
} else if (z > 5) {
console.log("z is greater than 5 but not greater than 10");
} else {
console.log("z is not greater than 5");
}
Key Points:
- Conditions are evaluated as either true or false.
- Comparison operators (>, <, >=, <=, ===, !==) and logical operators (&&, ||, !) are often used in conditions.
- Code blocks are enclosed in curly braces {}.
- Conditional statements are essential for controlling the flow of your program and making decisions based on different situations.
Top comments (0)