Conditional Statements in JavaScript
By Syncfusion®, Inc. · Last updated
Making decisions with if, if...else, else if and nested if, matching one value against many cases with switch, and producing a value with the ternary operator.
What Is a Conditional Statement?
Conditional statement = code that runs only when a condition is true.
if: run this when the condition is true.else: otherwise, run this.switch: pick one case from many.
Simple lesson: conditionals let your program make choices, like a shopkeeper deciding what to say.
A Real-World Example
A product card shows In stock when stock is above 5. It shows Only 2 left! when stock is 1 to 5. It shows Sold out when stock is 0, and hides the Buy button.
stock = 2
if?
> 5 → In stock
1–5 → Only 2 left!
else → Sold out
The value travels down only one road: the first condition that is true.
Every box runs when you press Run. Edit a value and run again to see a different branch.
What You Will Learn
if,if...elseandelse ifchains.- Nested
if, and flatter guard clauses. switch,breakanddefault.- The ternary
? :for small choices.
if statement
The block in { } runs only when the condition is true.
The message prints only when the cart has items
const itemsInCart = 2;
if (itemsInCart > 0) {
console.log("Ready to check out");
}
console.log("Done");
Expected output:
Ready to check out
Done
The condition does not have to be a boolean. Truthy values count as true:
A name and an empty string, used directly as conditions
const name = "Asha";
const coupon = "";
if (name) {
console.log("Hello,", name);
}
if (coupon) {
console.log("Coupon applied");
}
Expected output:
Hello, Asha
if...else statement
else runs when the condition is false. Exactly one of the two blocks runs.
Free delivery over 499, a delivery charge otherwise
const total = 320;
if (total >= 499) {
console.log("Free delivery");
} else {
console.log("Delivery: ₹40");
}
Expected output:
Delivery: ₹40
else if
Checks run from the top. The first true one wins, and the rest are skipped.
Stock turned into a label, one condition at a time
const stock = 2;
if (stock > 5) {
console.log("In stock");
} else if (stock > 0) {
console.log(`Only ${stock} left!`);
} else {
console.log("Sold out");
}
Expected output:
Only 2 left!
So the order matters. Put the strictest check first:
The same labels in the wrong order, and every product looks plentiful
const stock = 2;
if (stock > 0) {
console.log("In stock");
} else if (stock > 5) {
console.log("Plenty left");
} else {
console.log("Sold out");
}
Expected output:
In stock
nested if
An if inside another if checks the second thing only when the first is true.
The discount is checked only after the account is confirmed
const isSignedIn = true;
const isMember = true;
if (isSignedIn) {
if (isMember) {
console.log("10% member discount");
} else {
console.log("Join to save 10%");
}
} else {
console.log("Please sign in");
}
Expected output:
10% member discount
Deep nesting is hard to read. A guard clause returns early instead:
The same checks, written flat with guard clauses
function discountMessage(isSignedIn, isMember) {
if (!isSignedIn) return "Please sign in";
if (!isMember) return "Join to save 10%";
return "10% member discount";
}
console.log(discountMessage(true, true));
console.log(discountMessage(false, true));
Expected output:
10% member discount
Please sign in
switch statement
switch compares one value against many cases with ===.
breakleaves the switch.defaultruns when no case matches.
One order status matched against four cases
const status = "shipped";
switch (status) {
case "pending":
console.log("We got your order");
break;
case "shipped":
console.log("On the way");
break;
case "delivered":
console.log("Enjoy!");
break;
default:
console.log("Unknown status");
}
Expected output:
On the way
Forget break, and the code falls through into the next cases:
A missing break makes three messages print instead of one
const status = "pending";
switch (status) {
case "pending":
console.log("We got your order");
case "shipped":
console.log("On the way");
case "delivered":
console.log("Enjoy!");
}
Expected output:
We got your order
On the way
Enjoy!
Fall-through is useful when two cases share one answer:
Saturday and Sunday share one branch
const day = "Sunday";
switch (day) {
case "Saturday":
case "Sunday":
console.log("Weekend sale: 20% off");
break;
default:
console.log("Regular prices");
}
Expected output:
Weekend sale: 20% off
Conditional (ternary) operator (?:)
For a choice between two values, a ternary is shorter than if...else.
Picking a word for a message with one ternary
const count = 1;
const word = count === 1 ? "item" : "items";
console.log(`You have ${count} ${word} in your cart`);
Expected output:
You have 1 item in your cart
Nested ternaries are hard to read. Use an if chain for three or more choices:
A nested ternary and the if chain that says the same thing
const stock = 0;
const label = stock > 5 ? "In stock" : stock > 0 ? "Few left" : "Sold out";
console.log(label);
let same;
if (stock > 5) same = "In stock";
else if (stock > 0) same = "Few left";
else same = "Sold out";
console.log(same);
Expected output:
Sold out
Sold out
Conditionals on a Web Page
Pick a label and a colour from the stock, and hide the Buy button when it is sold out. Change stock to 8, 3 and 0.
A product card that changes with the stock
const stock = 3;
const stockLine = document.querySelector("#stock");
document.querySelector("#name").textContent = "Steel bottle";
document.querySelector("#price").textContent = "₹299";
if (stock > 5) {
stockLine.textContent = "In stock";
stockLine.style.color = "green";
} else if (stock > 0) {
stockLine.textContent = `Only ${stock} left!`;
stockLine.style.color = "darkorange";
} else {
stockLine.textContent = "Sold out";
stockLine.style.color = "crimson";
}
const buy = document.createElement("button");
buy.textContent = "Buy now";
buy.disabled = stock === 0;
document.querySelector("#card").append(buy);
console.log("label:", stockLine.textContent, "| buy enabled:", !buy.disabled);
Easy way to remember: an if chain is a queue. The first true condition gets served, and everyone after it goes home.
TL;DR
ifruns a block when the condition is true;elsecovers the rest.- In an
else ifchain only the first true branch runs, so order matters. - Guard clauses (
if (!ok) return ...) keep code flat. switchuses===. Every case needsbreak, unless you want fall-through.- Use
? :to choose between two values.
Try this
In the switch example, change status to "Shipped" with a capital S. It prints Unknown status, because === treats upper and lower case as different.
Check Yourself
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
if (stock = 0) | = compares | Use === to compare | The value is changed and the check is wrong |
> 0 before > 5 in a chain | All true branches run | Only the first true branch runs | Later branches never run |
A case with no break | Each case stops by itself | Code falls into the next case | Several messages print |
case "1": for the number 1 | switch converts types | switch uses === | The case never matches |
if (items) when items is [] | An empty array is false | [] is truthy | The empty-cart message never shows |
Quick reference
| Syntax | Meaning |
|---|---|
if (condition) { ... } | run the block only when the condition is truthy |
if (condition) { ... } else { ... } | run exactly one of the two blocks |
else if (condition) { ... } | test another condition; the first true one wins |
if (a) { if (b) { ... } } | a nested if: b is checked only after a passes |
if (!ok) return; | a guard clause that leaves early instead of nesting |
switch (value) { case x: ...; break; } | compare one value against exact cases with === |
default: | the block that runs when no case matches |
condition ? a : b | give back a when the condition is truthy, otherwise b |
Exercises
What to Remember
- Conditionals choose which code runs.
- Order an
else ifchain from the strictest check to the loosest. switchfor one value against many cases;? :for two values.
Next: Loops. Run the same code again and again, once for each item.