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
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


Top comments (2)
The conditional (ternary) operator is not a shorthand for the if statement. It's an operator, not a statement. It forms part of an expression, and is not a control flow statement.
It will evaluate one of two operands based on the truthiness of the first operand. It cannot run other statements or blocks of statements like
ifand other control flow statements can.It's similar, but certainly not shorthand for an if/else.
Spot on! Thank you for the excellent clarification. You are absolutely rightβthe conditional operator evaluates an expression and returns a value, whereas if/else is a control flow statement that executes blocks of code. I appreciate you pointing out this technical distinction, and I'll update the post to reflect this accurately. Thanks for reading!