Loading...
Loading...
Make decisions in code. Execute different paths based on conditions.
Conditional statements let JavaScript choose which code to run. An if statement runs its block only when the condition is truthy; else if and else handle the other cases; switch compares one value against many options. Every condition is converted to true or false, so knowing which values are falsy matters.
Step through this example in the visualizer
Control flow is how programs decide what to do next. If a user is logged in, show the dashboard; otherwise, redirect to login. If a cart total exceeds a threshold, apply a discount. These everyday behaviors all depend on conditionals and loops.
This module walks through if/else, switch, for and while loops, and how to combine them without losing readability. Visual step-throughs help you see exactly which branch runs and how loop counters change on each iteration.
Every program makes decisions: showing an error, picking a price, redirecting a logged-out user. Conditionals are where those decisions live, and many beginner bugs come from a condition that is unexpectedly truthy or falsy, or from branches checked in the wrong order.
Execute code only when a condition is true.
The if statement evaluates a condition. If the result is true, the code block executes. If false, it's skipped entirely.
if (condition) { // code runs ONLY if condition is true } // Example: if (temperature > 30) { console.log("It's hot outside!"); }
> "It's hot outside!"
Two branches: one for true, one for false.
if (age >= 18) { console.log("You can vote!"); } else { console.log("Too young to vote."); }
> "You can vote!"
// else runs when condition is false let hour = 14; let greeting; if (hour < 12) { greeting = "Good morning"; } else { greeting = "Good afternoon"; } console.log(greeting);
Multiple conditions checked in order.
if (score >= 90) { grade = "A"; } else if (score >= 80) { grade = "B"; } else if (score >= 70) { grade = "C"; } else if (score >= 60) { grade = "D"; } else { grade = "F"; }
💡 Conditions are checked top to bottom. The first match wins: remaining conditions are not evaluated.
Any value can be used as a condition.
JavaScript automatically converts values to boolean in conditions. Values that become false are called falsy. Everything else is truthy.
Falsy Values (6 total)
falseboolean false0zero""empty stringnullno valueundefinednot assignedNaNnot a numberTruthy (everything else)
"hello"non-empty string42non-zero number[]empty array!{}empty object!"0"string "0"!"false"string "false"!if (hello) → true (truthy: block runs)
// Common patterns using truthy/falsy: let name = ""; if (name) { console.log("Has name"); // skipped: "" is falsy } let items = []; if (items.length) { console.log("Has items"); // skipped: 0 is falsy } let user = getUser(); if (user) { console.log(user.name); // safe: only runs if user exists }
Match a value against multiple cases.
switch (expression) { case value1: // code for value1 break; case value2: // code for value2 break; default: // code if no case matches }
case "Wednesday": → Weekday 💼
// Real example: switch (day) { case "Monday": case "Tuesday": case "Wednesday": case "Thursday": case "Friday": type = "Weekday"; break; // ← DON'T forget break! case "Saturday": case "Sunday": type = "Weekend"; break; default: type = "Invalid day"; }
// Without break: "fall through": switch (2) { case 1: console.log("one"); case 2: console.log("two"); // ← matches here case 3: console.log("three"); // ← also runs! } // Output: "two", "three"
Without break, execution 'falls through' to the next case. This is usually a bug!
Write cleaner conditional code.
Use early returns to reduce nesting
function getDiscount(user) {
if (!user) return 0;
if (!user.isPremium) return 5;
return 20;
}function getDiscount(user) {
if (user) {
if (user.isPremium) {
return 20;
} else {
return 5;
}
} else {
return 0;
}
}Prefer === over ==
if (value === "") { ... }
if (count === 0) { ... }if (value == "") { ... } // "" == 0 is true!
if (count == false) { ... }Use switch for many values
switch (status) {
case "loading": return <Spinner />;
case "error": return <Error />;
case "success": return <Data />;
}if (status === "loading") return <Spinner />; else if (status === "error") return <Error />; else if (status === "success") return <Data />;
Test your understanding.
What does this output?
const x = 0;
if (x) {
console.log("yes");
} else {
console.log("no");
}Which values are falsy in JS? Name one besides 0.
What keyword handles multiple fixed value comparisons?
What does this output?
const age = 20;
const msg = age >= 18 ? "adult" : "minor";
console.log(msg);Common questions about conditionals.
Test your understanding: 3 questions
What will be logged?
let age = 18;
if (age >= 18) {
console.log("adult");
} else {
console.log("minor");
}