Make Your Code Choose
JavaScript If/Else
Run different code based on a condition. `if`, `else if`, and `else` are the workhorses of every program.
What you'll learn
- Run code conditionally with `if`
- Chain conditions with `else if`
- Provide a fallback with `else`
- Watch out for assignment instead of comparison
The if statement runs a block of code only when a condition is
true. It’s the most basic form of decision-making in code.
const age = 21;
if (age >= 18) {
console.log("You're an adult.");
} else — the fallback
Use else for what to do when the condition is false.
const hour = 14;
if (hour < 12) {
console.log("Good morning!");
} else {
console.log("Good afternoon!");
} else if — multiple conditions
Stack else if for more than two options.
const score = 78;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else if (score >= 60) {
console.log("D");
} else {
console.log("F");
}
// "C" JavaScript checks each condition top to bottom and runs the first one that’s true. Order matters.
Truthy Conditions
The condition doesn’t have to be a comparison — any value works.
JavaScript converts it to a boolean. (Refresher: the eight falsy
values are false, 0, -0, 0n, "", null, undefined, NaN.)
const name = "Ada";
if (name) {
console.log(`Hello, ${name}!`);
} else {
console.log("No name provided.");
} This is a common idiom for “if the variable has a meaningful value.”
A Classic Mistake: = vs ===
= is assignment, not comparison. Mixing them up is a famous bug.
const age = 21;
// BUG: assignment, not comparison
// if (age = 18) { … }
// This would assign 18 to age (impossible with const — TypeError).
// With let, the condition becomes "is 18 truthy?" which is always true.
// CORRECT:
if (age === 18) {
console.log("Just became an adult.");
} Skipping the Braces
For a single statement, you can drop the { }. Most teams require
them anyway — they avoid bugs when someone later adds a second line.
// Legal:
if (loggedIn) showDashboard();
// Preferred:
if (loggedIn) {
showDashboard();
} Try It Yourself
Exercise
Discount calculator
const total = 120;
// your code here
💡 Show hint
✅ Show solution
const total = 120;
let finalPrice;
if (total > 100) {
finalPrice = total * 0.9;
} else {
finalPrice = total;
}
console.log(finalPrice);
Up Next
For a quick yes/no choice between two values, JavaScript has a compact form — the ternary operator.
JavaScript Ternary →