JavaScript Conditional Statements
Conditional statements control the flow of your program by executing different code blocks based on conditions. JavaScript provides several ways to make decisions in your code.
Types of Conditional Statements
JavaScript has four main conditional constructs: if/else, switch, ternary operator, and logical operators for short-circuit evaluation.
| Statement | Best For | Example Use Case |
|---|---|---|
| if...else | 1-3 conditions | Check age range |
| else if | Multiple ranges/conditions | Grade calculation |
| switch | Many exact matches | Day of the week |
| ternary | Simple true/false assignments | Set status text |
| &&, || | Short-circuit defaults | Default values |
let score = 85;
// if...else
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B"); // This runs
} else {
console.log("Grade: C or below");
}
// Ternary
let passed = score >= 60 ? "Pass" : "Fail";
console.log(passed); // "Pass"
// Switch
let day = "Monday";
switch (day) {
case "Monday": console.log("Start of week"); break;
case "Friday": console.log("Almost weekend"); break;
default: console.log("Regular day");
}When to Use if vs switch
Use if/else when testing ranges, complex conditions, or boolean expressions. Use switch when comparing a single value against many specific options.
let status = "active";
let temperature = 35;
// Use if for ranges and complex conditions
if (temperature > 30 && status === "active") {
console.log("Warning: High temp while active");
}
// Use switch for exact value matching
switch (status) {
case "active":
console.log("System is running");
break;
case "paused":
console.log("System is paused");
break;
case "stopped":
console.log("System is stopped");
break;
default:
console.log("Unknown status");
}Truthy and Falsy Values
Every value in JavaScript is either truthy or falsy. When used in a condition, truthy values evaluate to true and falsy values evaluate to false. Understanding this is key to writing clean conditionals.
| Falsy Values | Truthy Values (Examples) |
|---|---|
| false | true |
| 0 | 42 (any non-zero number) |
| -0 | "hello" (any non-empty string) |
| "" (empty string) | [] (empty array) |
| null | {} (empty object) |
| undefined | function() {} |
| NaN | Infinity |
// Falsy values
if (0) console.log("never");
if ("") console.log("never");
if (null) console.log("never");
if (undefined) console.log("never");
if (NaN) console.log("never");
// Truthy values (even empty arrays and objects!)
if ([]) console.log("empty array is truthy!");
if ({}) console.log("empty object is truthy!");
if ("0") console.log("string '0' is truthy!");
// Common pattern: check if array has items
let items = [1, 2, 3];
if (items.length) {
console.log(`Found ${items.length} items`);
}Guard Clauses
A guard clause is a pattern where you handle edge cases early and return, keeping the main logic un-nested. This makes code more readable.
function processUser(user) {
// Guard clauses handle edge cases first
if (!user) {
console.log("No user provided");
return;
}
if (!user.name) {
console.log("User has no name");
return;
}
// Main logic (not nested)
console.log(`Processing: ${user.name}`);
}
processUser(null); // "No user provided"
processUser({}); // "User has no name"
processUser({ name: "Alice" }); // "Processing: Alice"