Introduction & Syntax
Conditional Statements · Study material
Every program makes decisions, and conditional statements are how JavaScript makes them. They look simple, but they are a favourite for output questions because of a few sharp edges: an if condition is converted to a boolean (so "0" and [] are true), switch compares with ===, a missing break falls through to the next case, an else belongs to the nearest if, and the order of an else-if ladder decides the result. This topic covers all of them, plus guard clauses and lookup tables used in professional code. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.
if, else and the else-if ladder
if (condition) { … } else if (other) { … } else { … } tests the conditions from top to bottom and runs only the first branch whose condition is true. Put the most specific (or highest) test first: checking marks >= 40 before marks >= 90 would give every topper a C.
// Only the FIRST condition that is true runs; the order of the tests matters
function grade(marks) {
if (marks >= 90) return "A+";
else if (marks >= 75) return "A";
else if (marks >= 60) return "B";
else if (marks >= 40) return "C";
else return "Fail";
}
console.log([95, 75, 62, 40, 12].map(grade).join(" "));
A+ A B C Fail
Truthy and falsy conditions
The condition can be any value; JavaScript converts it with Boolean(). The falsy values are false, 0, -0, 0n, "", null, undefined and NaN – everything else, including "0", "false", [] and {}, is truthy. Be careful when 0 or "" is a valid value: test count !== undefined or value != null instead of if (count).
// An if condition does not have to be a boolean: the value is converted with Boolean()
const inputs = ["", "Asha", 0, 42, null, [], {}];
for (const v of inputs) {
if (v) console.log(JSON.stringify(v), "→ truthy");
else console.log(JSON.stringify(v), "→ falsy");
}
"" → falsy
"Asha" → truthy
0 → falsy
42 → truthy
null → falsy
[] → truthy
{} → truthyswitch
switch (value) compares the value with each case using strict equality (===) and starts running at the first match. Execution then continues through the following cases until a break, return or the end of the switch – this fall-through is how cases are grouped, and forgetting a break is a classic bug. default runs when no case matches; it may be written anywhere, but it is still tried last.
function dayType(day) {
switch (day) {
case "Sat": // grouped cases: an empty case falls through to the next one
case "Sun":
return "Weekend";
case "Fri":
console.log("(almost the weekend)");
// no break or return: execution falls through into default
default:
return "Weekday";
}
}
console.log(dayType("Sun"));
console.log(dayType("Fri"));
console.log(dayType("Mon"));
Weekend (almost the weekend) Weekday Weekday
// switch compares with === – no type conversion
const code = "1"; // e.g. read from a form field
switch (code) {
case 1:
console.log("number one");
break;
case "1":
console.log("string one");
break;
}
string one
switch (true) for ranges
A switch cannot test ranges directly, but switch (true) compares true with each case expression, so the first case whose condition is true wins. An else-if ladder does the same job and is often clearer.
// switch (true): the first case whose expression is true wins – handy for ranges
const bmi = 27.4;
let category;
switch (true) {
case bmi < 18.5: category = "Underweight"; break;
case bmi < 25: category = "Normal"; break;
case bmi < 30: category = "Overweight"; break;
default: category = "Obese";
}
console.log(category);
Overweight
The ternary operator
condition ? a : b is an expression, so it can be assigned, returned or used inside a template literal. Use it for a simple choice between two values; for actions or more than two outcomes, an if statement is more readable.
Guard clauses and early returns
Instead of nesting if inside if, handle invalid cases first and return immediately. The main logic then sits at the end, un-indented. This style is expected in professional code reviews.
// Guard clauses: reject bad cases first and return early – no deep nesting
function withdraw(balance, amount) {
if (typeof amount !== "number" || amount <= 0) return "Invalid amount";
if (amount > balance) return "Insufficient balance";
if (amount % 100 !== 0) return "Amount must be a multiple of 100";
return `Dispensed ${amount}, balance ${balance - amount}`;
}
console.log(withdraw(5000, -50));
console.log(withdraw(5000, 7000));
console.log(withdraw(5000, 250));
console.log(withdraw(5000, 1500));
Invalid amount Insufficient balance Amount must be a multiple of 100 Dispensed 1500, balance 3500
Lookup tables instead of long switches
When each case only maps an input to a value, an object (or a Map) is shorter, faster to extend and easy to test. Combine it with ?? for a default.
// An object lookup replaces a switch that only maps values to values
const SHIPPING = { standard: 40, express: 120, overnight: 250 };
function shippingCost(type) {
return SHIPPING[type] ?? "Unknown shipping type";
}
console.log(shippingCost("express"), shippingCost("drone"));
120 Unknown shipping type
Common mistakes
- A semicolon after if (…) – the if controls an empty statement and the block always runs.
- = instead of === in a condition – it assigns, and the result is usually truthy.
- Forgetting break – execution falls through into the next case.
- Wrong ladder order – a broad test placed first catches everything.
- switch on a string from input with number cases – === never matches "2" with 2.
- if (count) when 0 is valid – 0 is falsy.
- No braces with nested ifs – the else attaches to the nearest if.
Key points to remember
- Only the first true branch of an if / else-if chain runs.
- Conditions are converted to booleans: eight falsy values, everything else truthy.
- switch uses ===; without break it falls through.
- default can be anywhere but is chosen only when nothing matches.
- An else pairs with the nearest unmatched if – always use braces.
- The ternary is an expression; if is a statement.
- Prefer guard clauses and lookup tables to deep nesting and huge switches.
Frequently asked questions
Is switch faster than if…else?
For a handful of cases there is no meaningful difference. Choose the clearer one: switch for many fixed values of one variable, if…else for ranges and mixed conditions, an object lookup for value-to-value mapping.
Can a switch case use expressions?
Yes. Each case expression is evaluated in order until one matches with ===, which is what makes switch (true) work.
Should I use the ternary operator?
For short value choices, yes. Avoid nesting more than one level deep; it quickly becomes unreadable.
Where can I learn more?
Read if, else and switch and JavaScript Operators in the JavaScript tutorial, then practise with the exercises below.