Conditions are used to make decisions in code. They allow a program to execute different blocks of code based on different conditions.
The if statement is used to execute a block of code only when a condition is true.
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote");
}Note: If the condition evaluates to
false, the code inside theifblock will not run.
The if else statement is used when you want to run one block of code if the condition is true and another block if it is false.
let age = 16;
if (age >= 18) {
console.log("You are eligible to vote");
} else {
console.log("You are not eligible to vote");
}Note:
elseruns only when theifcondition fails.
A nested if else is an if else statement placed inside another if or else block.
It is used when multiple conditions depend on each other.
let age = 20;
let hasLicense = true;
if (age >= 18) {
if (hasLicense) {
console.log("You can drive");
} else {
console.log("You need a license to drive");
}
} else {
console.log("You are underage");
}Note: Nested
if elseis useful when conditions are hierarchical and must be checked step by step.
The ternary operator is a shorter way to write an if else statement.
It is mostly used for simple conditions.
let age = 20;
let result = age >= 18 ? "Eligible" : "Not Eligible";
console.log(result); // EligibleNote: Use the ternary operator only when the logic is simple and easy to read.
A nested ternary is a ternary operator placed inside another ternary operator.
It allows you to handle multiple conditions in a single expression.
let score = 75;
let grade = score >= 90 ? "A" : score >= 75 ? "B" : score >= 60 ? "C" : "Fail";
console.log(grade); // BThe switch statement is used when you need to compare one value against multiple possible cases.
let currentDay = 3;
switch (currentDay) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}Note:
breakstops the execution of the switch block.- Without
break, execution will continue to the next case (fall-through).defaultruns when no case matches.