How to Write If Else Statements in JS: Full Guide
Learn how to write if/else statements in JavaScript with clear syntax, practical examples, and common mistake fixes for beginners.
An if/else statement gives your code two possible paths. If the condition is true, the if block runs. If the condition is false, the else block runs. Exactly one of the two will execute, never both.
const hour = 14;
if (hour < 12) {
console.log("Good morning.");
} else {
console.log("Good afternoon.");
}
// "Good afternoon." prints because 14 is not less than 12This is the pattern: a condition, a block for the true case, and a block for the false case.
The if/else Syntax
if (condition) {
// runs when condition is true
} else {
// runs when condition is false
}Every part is required for a complete if/else:
- if: the keyword that starts the decision.
- (condition): an expression evaluated as true or false.
- First { }: the if body, runs when the condition is true.
- else: the keyword that introduces the fallback path.
- Second { }: the else body, runs when the condition is false.
If you leave out the else block, you have a plain if statement instead.
Writing Conditions That Read Well
A good condition is easy to understand at a glance. Negating a condition with ! often makes the reader work harder to follow the logic:
// Harder to read: negated condition
if (!user.isBanned) {
showContent();
} else {
showBannedMessage();
}Flipping the condition to its positive form and swapping the two blocks produces the exact same behavior, but reads more naturally:
// Easier to read: positive condition, swap the blocks
if (user.isBanned) {
showBannedMessage();
} else {
showContent();
}Both versions do the same thing, but the second one reads like a sentence: "If the user is banned, show the banned message. Otherwise, show the content." Prefer positive conditions and put the common or expected case first.
Practical Examples
Checking user input
const username = prompt("Enter your username:");
if (username && username.length >= 3) {
console.log("Username is valid.");
} else {
console.log("Username must be at least 3 characters.");
}The condition does two things: first, it checks that username is not empty (truthy check), then it checks the length. If the user clicks Cancel, prompt() returns null, and the first part short-circuits so the length check is never evaluated.
Handling a numeric threshold
const temperature = 22;
if (temperature > 30) {
console.log("Stay hydrated. It is hot outside.");
} else {
console.log("Weather is comfortable.");
}Displaying different UI states
The same pattern also works for choosing between two UI states, such as a loading indicator and the finished content, without needing any different syntax:
const isLoading = false;
if (isLoading) {
console.log("Rendering spinner...");
} else {
console.log("Rendering content...");
}Each example follows the same pattern: a clear condition that evaluates to true or false, a block for each outcome, and a single log statement that confirms which path ran.
Common Mistakes
Forgetting the parentheses around the condition
// Wrong: syntax error
if isLoggedIn {
console.log("Hi");
}
// Right
if (isLoggedIn) {
console.log("Hi");
}The parentheses are not optional. JavaScript requires them around every condition, and leaving them out is a syntax error rather than a warning.
Missing curly braces on multi-line bodies
Another common mistake happens with braces instead of parentheses, and it is more dangerous because it does not throw an error at all:
// Wrong: only the first console.log is inside the else
if (isAdmin) {
console.log("Admin panel");
} else
console.log("Loading user view...");
console.log("Tracking page visit..."); // Always runs!Both if and else bodies should use curly braces, even when they contain one statement. It prevents bugs when you add a second statement later.
Using else when no fallback is needed
// Overcomplicated: an empty else does nothing
if (notificationsEnabled) {
showNotifications();
} else {
// nothing to do here
}
// Simpler: just use if
if (notificationsEnabled) {
showNotifications();
}If the else block is empty, remove it. An if without else is perfectly valid and clearer about your intent.
When to use if/else vs a ternary
For simple value assignments, a ternary operator can replace a short if/else:
// if/else (4 lines)
let label;
if (isMember) {
label = "Member";
} else {
label = "Guest";
}
// Ternary (1 line, same result)
const label = isMember ? "Member" : "Guest";Use if/else when each branch does multiple things or when the logic is complex enough that a ternary would be hard to read. Use a ternary when you are simply picking between two values to assign.
Nesting if/else
You can put one if/else inside another. This is how you handle decisions that depend on a prior check:
const isLoggedIn = true, isAdmin = false;
if (isLoggedIn) {
if (isAdmin) {
console.log("Welcome, Admin.");
} else {
console.log("Welcome, User.");
}
} else {
console.log("Please log in.");
}
// "Welcome, User." printsThe outer if checks login status. Only if the user is logged in does the inner if check the role. This pattern is common, but if you find yourself nesting more than two levels deep, consider using an else if chain instead. See chaining multiple conditions with else if.
Rune AI
Key Insights
- if/else provides two code paths: one for true, one for false.
- The else block runs only when the if condition is false.
- The condition goes in parentheses: if (condition) { ... } else { ... }.
- Exactly one branch runs -- if and else are mutually exclusive.
- You can nest if/else inside other if/else blocks.
- Keep conditions simple. Extract complex logic into a named function or variable.
Frequently Asked Questions
Can I have an if without an else?
Can I have multiple else blocks?
What happens if the if condition is true but the else block also has code that could run?
Conclusion
An if/else statement gives your code two paths: one for when a condition is true, and one for when it is false. The syntax is simple: if (condition) { ... } else { ... }. Write the condition as a comparison or a truthy/falsy check, put the true-path code in the if block, and put the false-path code in the else block. Keep conditions readable, use curly braces, and remember that exactly one branch runs, never both.
More in this topic
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.
How to Loop Through Arrays Using JS for Loops Guide
Looping through arrays is the most practical use of JavaScript for loops. Learn how to access each element by index, avoid off-by-one errors, and choose between for, for...of, and forEach.