JavaScript conditional statements are used to perform different actions based on different conditions. The most commonly used conditional statements are the if statement, the if-else statement, and the switch statement.
if Statement:
The if statement is used to check if a certain condition is true or false.
If the condition is true, the code inside the if block will be executed.
if (x > y) {
console.log("x is greater than y");
}
Example:
let x = 5;
if (x > 3) {
console.log("x is greater than 3");
}
if-else Statement:
The if-else statement is an extension of the if statement and allows for multiple conditions to be checked.
If the condition in the if statement is true, the code in the if block will be executed.
If the condition is false, the code in the else block will be executed.
if (x > y) {
console.log("x is greater than y");
} else {
console.log("x is not greater than y");
}
Example:
let y = 3;
if (y > 5) {
console.log("y is greater than 5");
} else {
console.log("y is not greater than 5");
}
else-if Statement:
The else-if statement allows for multiple conditions to be checked in a logical sequence.
If the first condition is true, the code in the corresponding block will be executed.
If the first condition is false, the next condition will be checked, and so on.
If none of the conditions are true, the code in the else block will be executed.
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 less than or equal to 10");
} else {
console.log("z is less than or equal to 5");
}
Switch Statement:
The switch statement is used to check multiple conditions against a single expression.
Each case in the switch statement corresponds to a different condition, and the code inside the case block will be executed if the condition is true.
switch (x) {
case 1:
console.log("x is 1");
break;
case 2:
console.log("x is 2");
break;
default:
console.log("x is not 1 or 2");
}
Example:
let day = "Monday";
switch (day) {
case "Monday":
console.log("It's Monday");
break;
case "Tuesday":
console.log("It's Tuesday");
break;
case "Wednesday":
console.log("It's Wednesday");
break;
default:
console.log("It's not Monday, Tuesday, or Wednesday");
}
Ternary Operator:
The ternary operator is a shorthand way of writing a simple if-else statement.
It takes the form of “condition ? value1 : value2”, where condition is the expression being evaluated, value1 is the value returned if the condition is true, and value2 is the value returned if the condition is false.
let a = 5;
let b = 10;
let result = (a > b) ? "a is greater than b" : "a is less than or equal to b";
console.log(result);
Note that the ternary operator can be nested to make more complex statements.