if...else
Run different code depending on a condition.
Syntax
if (condition) { ... } else { ... }The if statement runs a block of code only when a condition is true. Add else for an alternative, and else if for more choices.
Structure
Conditions go in parentheses; the code to run goes in braces. JavaScript checks each condition in order and runs the first that is true.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Show a different dashboard view depending on whether the logged-in user is an admin or a regular user.
- Display a contextual error message when a form field fails one of several validation rules.
- Redirect the user to the login page if they are not authenticated when they access a protected route.
More examples
Simple if-else branch
Checks a single condition and executes one of two branches based on whether it is true or false.
const age = 17;
if (age >= 18) {
console.log("Access granted");
} else {
console.log("Access denied – must be 18+");
}if-else if-else chain
Uses an if-else if chain to assign a letter grade based on which score range the value falls into.
const score = 72;
let grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "F";
}
console.log(grade); // "C"Guard clause with early return
Uses guard-clause if statements with early returns to handle edge cases before the main logic runs.
function processPayment(amount) {
if (amount <= 0) {
return "Invalid amount";
}
if (amount > 10000) {
return "Amount exceeds limit";
}
return `Payment of $${amount} accepted`;
}
console.log(processPayment(500));
Discussion