The if...else statement is the most basic way to make decisions in JavaScript — it lets your program run different code depending on whether a condition is true or false. Almost every program you write will use it, from validating a form field to deciding which part of the UI to show.
JavaScript evaluates the condition inside the parentheses, converts it to a boolean if it isn't already one, and runs the matching block. If no condition matches and there's no else, nothing happens at all.
Basic if...else Syntax
const age = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
Output:
You are an adult.
The else block is optional — if you only care about one case, you can leave it out entirely and just use a standalone if.
Chaining Conditions with else if
When you have more than two possible outcomes, chain additional conditions with else if. JavaScript checks each condition top to bottom and stops at the first one that's true.
const score = 72;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 75) {
console.log("Grade: B");
} else if (score >= 60) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
Output:
Grade: C
Order matters here — since 72 is also technically >= 60, but the 75 check comes first and fails, so JavaScript falls through to the next condition. Putting the broadest condition first would give the wrong answer.
Nested Conditions
You can put an if...else inside another one when a decision depends on more than one independent factor. Keep nesting shallow — more than two or three levels deep usually means the logic is better expressed with a switch statement or separate functions.
const isLoggedIn = true;
const isAdmin = false;
if (isLoggedIn) {
if (isAdmin) {
console.log("Welcome, admin!");
} else {
console.log("Welcome, user!");
}
} else {
console.log("Please log in.");
}
Output:
Welcome, user!
Any condition in an if statement doesn't have to be a strict boolean — JavaScript coerces it, which is closely tied to truthy and falsy values. Once you're comfortable with branching, the natural next step is repeating code with a for loop.
