In JavaScript, conditional statements
let your code make decisions based on
whether something is true or false.
The main ones are
if, else,
else if,
switch, and
the ternary operator
? :
1) if statement:
Use if when you want code to run only if a condition is true
let age = 20;
if (age >= 18) {
console.log("You are an adult");
}
Here, the message prints only when age >= 18 is true
2) if...else:
Use else when you want one block for true and another for false.
let age = 16;
if (age >= 18) {
console.log("You are an adult");
} else {
console.log("You are a minor");
}
If the condition is false, the else block runs instead
Flow Chart
3) if...else if...else:
Use else if when you have multiple conditions to check in order
let marks = 72;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 75) {
console.log("Grade B");
} else if (marks >= 60) {
console.log("Grade C");
} else {
console.log("Not Pass");
}
JavaScript checks each condition from top to bottom and runs the first matching block
Flow Chart:
4) switch:
Use switch when one value can match many different cases
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week");
break;
case "Friday":
console.log("Weekend soon");
break;
default:
console.log("Normal day");
}
switch is useful when you compare the same variable against several possible values
5) Ternary operator:
The ternary operator is a short form of if...else
let age = 19;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status);
It follows this pattern: condition ? expression1 : expression2
Simple rule:
Use
iffor one conditionUse
if...elsefor two outcomesUse
else iffor multiple conditionsUse
switchfor many fixed valuesUse
ternaryfor short, simple decisions
