JavaScript Conditions (if, else, switch, truthy/falsy)
Control flow in JavaScript: if/else branching, switch statements, truthy vs. falsy values, and early return guard clauses.
JavaScript Conditions (if, else, switch, truthy/falsy)
Conditional statements control the execution flow of programs based on boolean expressions.
1. Truthy and Falsy Values
In JavaScript, any value can be evaluated in a boolean context.
The 8 Falsy Values in JavaScript:
false0,-0,0n(BigInt zero)""(empty string)nullundefinedNaNdocument.all(legacy browser quirk)
Everything else is Truthy, including empty arrays [] and empty objects {}.
2. if, else if, and else
const role = "admin";
if (role === "admin") {
console.log("Full system access granted.");
} else if (role === "editor") {
console.log("Edit privileges granted.");
} else {
console.log("Read-only access.");
}3. The "Early Return" Guard Clause Pattern
Avoid deeply nested if/else ladders by returning early when invalid conditions occur:
// β Deeply nested (Hard to read and test)
function processPayment(user, cart) {
if (user) {
if (user.hasValidCard) {
if (cart.length > 0) {
return chargeUser(user, cart);
} else {
throw new Error("Cart is empty");
}
} else {
throw new Error("Invalid payment card");
}
} else {
throw new Error("User not authenticated");
}
}
// β
Guard Clauses (Flat, clean, easy to follow)
function processPayment(user, cart) {
if (!user) throw new Error("User not authenticated");
if (!user.hasValidCard) throw new Error("Invalid payment card");
if (cart.length === 0) throw new Error("Cart is empty");
return chargeUser(user, cart);
}4. The switch Statement
Use switch when checking a single variable against multiple exact values:
function getHttpStatusMessage(code) {
switch (code) {
case 200:
return "OK";
case 401:
return "Unauthorized";
case 404:
return "Not Found";
case 500:
return "Internal Server Error";
default:
return "Unknown Status";
}
}Related Topics
JavaScript Operators & Strict Equality
Mastering JavaScript operators: arithmetic, logical (&&, ||, ??), comparison (== vs ===), optional chaining (?.), and ternary expressions.
JavaScript Loops and Iteration
Mastering loops in JavaScript: for, while, do...while, for...of (iterables), for...in (keys), break, and continue.