JavaScript if / else: Conditional Statements Explained
JavaScript if / else statements let your code make decisions. They are the most common way to run one block of code when a condition is true and a different block when it is false.
Quick answer: Use if to test a condition, else if to check additional conditions, and else to handle everything that does not match earlier tests. The condition inside if is evaluated as a boolean-like value, so truthy values pass and falsy values fail.
Difficulty: Beginner
You'll understand this better if you know: basic JavaScript variables, values like true and false, and how expressions produce results.
1. What Is JavaScript if / else?
if / else is a control-flow statement that chooses between different paths in your program. It is used when the next action depends on a condition, such as a user being logged in, a number being positive, or a form field being empty.
- if runs code only when a condition is true.
- else runs code when the if condition is false.
- else if adds more checks before the final else.
- The condition can be any expression, not just a literal true or false.
In practice, if / else is how you express branching logic in plain JavaScript.
2. Why JavaScript if / else Matters
Programs rarely do the same thing every time. They react to data, user input, network responses, and state changes. if / else lets you adapt behavior without duplicating code or splitting your logic into many separate functions too early.
You use it when the program must choose:
- whether to show an error or success message
- whether a number is inside a valid range
- whether to continue, stop, or retry an operation
- whether to render one result or another in the browser
You usually avoid if / else only when a lookup table, a loop, or a simpler expression is clearer. The goal is readable decisions, not just fewer lines.
3. Basic Syntax or Core Idea
The syntax is simple: write a condition inside parentheses, then put the code to run inside curly braces.
Minimal if / else structure
if (condition) {
// runs when condition is truthy
} else {
// runs when condition is falsy
}The condition is an expression that JavaScript evaluates before choosing a branch. If it is truthy, the if block runs. Otherwise, the else block runs.
Adding else if branches
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "C";
}This structure checks conditions from top to bottom and stops at the first match.
4. Step-by-Step Examples
Example 1: Checking whether a number is positive
This example shows the most basic decision: one path for positive numbers and another for everything else.
const number = 12;
if (number > 0) {
console.log("Positive");
} else {
console.log("Zero or negative");
}If number is greater than zero, the first block runs. Otherwise, the else block handles the remaining cases.
Example 2: Choosing a message based on login state
You often use if / else with booleans, such as whether a user is logged in.
const isLoggedIn = true;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please sign in.");
}Because isLoggedIn is already a boolean, you do not need to compare it to true.
Example 3: Using else if for ranges
When a value can fall into several categories, else if makes the logic clearer.
const temperature = 24;
if (temperature >= 30) {
console.log("Hot");
} else if (temperature >= 20) {
console.log("Warm");
} else if (temperature >= 10) {
console.log("Cool");
} else {
console.log("Cold");
}The branches are evaluated in order, so you should place the most specific or highest-priority checks first.
Example 4: Using if / else with a function result
Conditions often depend on the result of a function, not just a variable.
function isEven(value) {
return value % 2 === 0;
}
const result = isEven(7);
if (result) {
console.log("Even");
} else {
console.log("Odd");
}This pattern is common when a check is reusable and should be named clearly.
5. Practical Use Cases
- Validate form input before sending it to a server.
- Show different messages based on payment status.
- Handle success and failure after an API request.
- Choose styling classes or text in a browser app.
- Guard against invalid values before continuing a calculation.
In browser code, if / else is often used to update the DOM after checking user input or application state.
6. Common Mistakes
Mistake 1: Using a single equals sign in the condition
A common beginner mistake is writing an assignment instead of a comparison. This changes the variable and makes the condition behave unexpectedly.
Problem: The condition uses =, which assigns a value instead of testing it. In JavaScript, that can lead to the wrong branch running and data being overwritten.
let mode = "edit";
if (mode = "view") {
console.log("View mode");
}Fix: Use === to compare values without changing them.
let mode = "edit";
if (mode === "view") {
console.log("View mode");
}The corrected version works because === checks equality without modifying the variable.
Mistake 2: Forgetting braces and confusing which statement belongs to else
Without braces, only the next statement belongs to the branch. This often creates logic that looks right but behaves incorrectly.
Problem: The else applies only to the first statement after it, which can make later lines run unconditionally.
const isReady = false;
if (isReady)
console.log("Start");
else
console.log("Wait");
console.log("Checking status...");Fix: Use braces for every multi-line branch so the grouping is obvious.
const isReady = false;
if (isReady) {
console.log("Start");
} else {
console.log("Wait");
console.log("Checking status...");
}The corrected version works because both statements are clearly part of the else block.
Mistake 3: Putting conditions in the wrong order
With else if, the first matching condition wins. If a broad condition appears before a narrow one, the narrow branch may never run.
Problem: score >= 50 catches values that should have matched the later, more specific checks first.
const score = 95;
if (score >= 50) {
console.log("Pass");
} else if (score >= 90) {
console.log("Excellent");
}Fix: Put the most specific or highest-priority condition first.
const score = 95;
if (score >= 90) {
console.log("Excellent");
} else if (score >= 50) {
console.log("Pass");
}The corrected version works because the stronger condition gets a chance to match first.
7. Best Practices
Practice 1: Keep conditions readable and specific
Prefer conditions that describe intent clearly. Long, hard-to-read expressions are harder to debug and easier to misinterpret later.
// Less clear
if (user && user.role === "admin" && user.isActive) {
console.log("Allow access");
}Break complex decisions into named booleans when the logic grows.
const isAdmin = user && user.role === "admin";
const canAccess = isAdmin && user.isActive;
if (canAccess) {
console.log("Allow access");
}This makes the decision easier to review and update.
Practice 2: Put the most likely or most important case first
When several branches are possible, order them by priority. That can make the code easier to read and can reduce unnecessary checks.
function describeStatus(status) {
if (status === "error") {
return "Something went wrong";
}
if (status === "loading") {
return "Please wait";
}
return "Ready";
}Putting the important branches first helps readers understand the flow quickly.
Practice 3: Use early returns when the logic is simpler
Sometimes a long if / else chain can be simplified with early returns inside a function. This reduces nesting and makes the main case easier to see.
function formatName(name) {
if (!name) {
return "Anonymous";
}
return name.trim();
}This pattern is often clearer than nesting the positive case inside an else block.
8. Limitations and Edge Cases
- if / else checks conditions in order and stops at the first match, so later branches may never run if an earlier condition is too broad.
- JavaScript uses truthy and falsy values, so values like 0, "", null, undefined, and NaN behave like false in conditions.
- Some values that look false are actually truthy, such as the string "0" or an empty array [].
- Large nested if / else structures can become hard to read; in those cases, consider helper functions, lookup objects, or early returns.
- Missing braces do not always cause syntax errors, but they can cause subtle logic bugs that are difficult to spot.
Note: In browser code, a condition based on user input may produce strings, not numbers. Always check the actual type before assuming a value is zero, empty, or invalid.
9. Practical Mini Project
This mini project builds a small age check that prints a message based on the entered value. It demonstrates a simple real-world decision flow.
function getTicketMessage(age) {
if (age < 0) {
return "Age cannot be negative.";
} else if (age < 13) {
return "Child ticket";
} else if (age < 18) {
return "Teen ticket";
} else {
return "Adult ticket";
}
}
const ages = [8, 15, 22, -1];
for (const age of ages) {
console.log(age, "->", getTicketMessage(age));
}This example combines a function, multiple branches, and a loop to show how if / else fits into a real program.
10. Key Points
- if runs code only when a condition is truthy.
- else handles the fallback case.
- else if lets you test several conditions in order.
- Order matters because JavaScript stops at the first matching branch.
- Braces improve readability and prevent logic mistakes.
- Truthiness matters: not every value behaves like a strict boolean.
11. Practice Exercise
Write a function that returns a message for a given points value.
- If points are less than 0, return "Invalid score".
- If points are less than 50, return "Needs improvement".
- If points are less than 80, return "Good".
- Otherwise, return "Excellent".
Expected output: The function should return different strings based on the numeric score.
Hint: Check the lowest and most specific cases first, then move upward.
Solution:
function getScoreMessage(points) {
if (points < 0) {
return "Invalid score";
} else if (points < 50) {
return "Needs improvement";
} else if (points < 80) {
return "Good";
}
return "Excellent";
}
console.log(getScoreMessage(42));
console.log(getScoreMessage(91));12. Final Summary
JavaScript if / else statements are the foundation of branching logic. They let your code react to different inputs and choose the correct path based on conditions.
To use them well, keep your conditions clear, order your branches carefully, and remember that JavaScript evaluates values using truthy and falsy rules. As your code grows, prefer readable decisions over clever shortcuts.
Next, practice combining if / else with functions, loops, and form validation so you can recognize the pattern in real projects.