Conditional statements are used to make decisions in a program.
They check whether a condition is true or false.
JavaScript provides if, else, and else if for conditional statements.
These statements help decide which block of code should run.
They are commonly used when a program needs to make a decision.
If Statement
- The if statement is used to check a condition.
- If the condition is true, the code inside the if block will run.
- If the condition is false, the code inside the block will not run.
Example:
let age = 20;
if (age >= 18) {
console.log("You are eligible to vote");
}
Output:
You are eligible to vote
Else Statement
- The else statement is used when the if condition is false.
- It provides an alternative block of code to run.
- If the if condition is true, the else block will not run.
- It is used to handle the opposite condition.
- else is always used with an if statement.
Example:
let age = 16;
if (age >= 18) {
console.log("You are eligible to vote");
} else {
console.log("You are not eligible to vote");
}
Output:
You are not eligible to vote
Else If Statement
- The else if statement is used to check another condition.
- It is used when the first if condition is false.
- We can use multiple else if conditions in a program.
- The first true condition will be executed.
- It is useful for checking multiple conditions.
Example:
let mark = 75;
if (mark >= 90) {
console.log("A Grade");
} else if (mark >= 60) {
console.log("B Grade");
} else {
console.log("C Grade");
}
Output:
B Grade
nested
Nested If Statement
A nested if means using an if statement inside another if statement.
The inner if condition is checked only when the outer if condition is true.
It is used to check conditions step by step.
A nested if can have another if inside it.
This helps handle multiple levels of conditions.
Example:
let age = 20;
let hasId = true;
if (age >= 18) {
if (hasId) {
console.log("Entry allowed");
}
}
Output:
Entry allowed
swited
Switch Statement
The switch statement is used to check a value against multiple cases.
It runs the code for the matching case.
-
The break statement stops the switch after a match.
- The default case runs when no case matches.
It is useful when we have multiple possible values.
Example:
let day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Invalid day");
}
Output:
Tuesday
Ternary Operator (? :)
- The ternary operator is a short form of if...else.
*It checks a condition and returns one of two values.
? is used for the true condition.
: is used for the false condition.
It is useful for writing simple conditions in one line.
Example:
let age = 20;
let result = age >= 18 ? "Eligible" : "Not Eligible";
console.log(result);
Output:
Eligible

Top comments (0)