In JavaScript, conditional statements allow you to execute different blocks of code based on specific conditions. They help your program make decisions, just like we do in everyday life.
For example, if a user is logged in, you can show their dashboard. Otherwise, you can display a login page.
In this tutorial, you will learn how to use if, else if, and else statements in JavaScript with simple examples, syntax, and practical use cases.
What Are Conditional Statements in JavaScript?
Conditional statements execute code depending on whether a condition is true or false.
JavaScript provides three commonly used conditional keywords:
if— executes code when a condition is true.else if— checks another condition when the previous condition is false.else— executes code when none of the previous conditions are true.
Let’s understand each one with examples.
1. JavaScript if Statement
The if statement executes a block of code only when the specified condition evaluates to true.
Syntax
if (condition) {
// Code runs if the condition is true
}
Example
let age = 20;
if (age >= 18) {
console.log("You are eligible to vote.");
}
Output:
You are eligible to vote.
Explanation
- The variable
agecontains the value20. - The condition
age >= 18checks whether the age is at least 18. - Since the condition is true, JavaScript executes the code inside the
ifblock.
If the condition were false, JavaScript would skip the block.
Example When the Condition Is False
let age = 16;
if (age >= 18) {
console.log("You are eligible to vote.");
}
console.log("Program finished.");
Output:
Program finished.
The message inside the if block is not displayed because the condition is false.
2. JavaScript else Statement
The else statement executes a block of code when the if condition is false.
An else statement must be used with an if statement.
Syntax
if (condition) {
// Runs if the condition is true
} else {
// Runs if the condition is false
}
Example
let age = 16;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
Output:
You are a minor.
Explanation
The condition age >= 18 is false because the age is 16. Therefore, JavaScript executes the else block.
Practical Example: Checking Login Status
let isLoggedIn = false;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in to continue.");
}
Output:
Please log in to continue.
This example uses a Boolean variable to decide which message to display.
3. JavaScript else if Statement
The else if statement allows you to check multiple conditions in sequence.
JavaScript checks each condition from top to bottom. When it finds the first true condition, it executes that block and skips the remaining branches.
Syntax
if (condition1) {
// Runs if condition1 is true
} else if (condition2) {
// Runs if condition1 is false and condition2 is true
} else if (condition3) {
// Runs if the previous conditions are false
} else {
// Runs if all conditions are false
}
You can use as many else if branches as needed.
Example: Checking Student Grades
let marks = 75;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 75) {
console.log("Grade B");
} else if (marks >= 60) {
console.log("Grade C");
} else if (marks >= 40) {
console.log("Grade D");
} else {
console.log("Fail");
}
Output:
Grade B
Explanation
JavaScript checks the conditions in order:
marks >= 90— false.marks >= 75— true.- JavaScript displays
Grade Band skips the remaining conditions.
Important: The order of conditions matters. For example, if you check marks >= 40 first, a student with 75 marks would receive Grade D because the first condition would already be true.
4. Difference Between if, else if, and else
| Statement | Purpose | Required? |
|---|---|---|
if | Checks the first condition | Yes, to start the chain |
else if | Checks another condition | No |
else | Handles all remaining cases | No |
An if statement can be used alone. An else if statement must follow an if or another else if. An else statement must come at the end of the conditional chain.
5. Real-World Examples of Conditional Statements
Example 1: Check Positive, Negative, or Zero
let number = -5;
if (number > 0) {
console.log("Positive number");
} else if (number < 0) {
console.log("Negative number");
} else {
console.log("Zero");
}
Output:
Negative number
This example checks whether a number is positive, negative, or zero.
Example 2: Check Whether a Number Is Even or Odd
let number = 7;
if (number % 2 === 0) {
console.log("Even number");
} else {
console.log("Odd number");
}
Output:
Odd number
The % operator returns the remainder after division. If a number divided by 2 has a remainder of zero, it is even.
Example 3: Check Discount Eligibility
let purchaseAmount = 1500;
if (purchaseAmount >= 2000) {
console.log("You get a 20% discount.");
} else if (purchaseAmount >= 1000) {
console.log("You get a 10% discount.");
} else {
console.log("No discount available.");
}
Output:
You get a 10% discount.
This logic can be used in an e-commerce application to calculate discounts based on an order amount. In a real application, the discount calculation and eligibility rules should be handled separately when needed.
Example 4: Check Temperature
let temperature = 32;
if (temperature >= 35) {
console.log("It is very hot.");
} else if (temperature >= 25) {
console.log("The weather is warm.");
} else if (temperature >= 15) {
console.log("The weather is pleasant.");
} else {
console.log("It is cold.");
}
Output:
The weather is warm.
The program checks the temperature and displays the matching message.
6. Using Logical Operators with if Statements
You can combine multiple conditions using logical operators.
Using the AND Operator (&&)
The && operator returns true when both conditions are true.
let age = 25;
let hasLicense = true;
if (age >= 18 && hasLicense) {
console.log("You can drive.");
} else {
console.log("You cannot drive.");
}
Output:
You can drive.
Using the OR Operator (||)
The || operator returns true when at least one condition is true.
let isAdmin = false;
let isManager = true;
if (isAdmin || isManager) {
console.log("You can access the management panel.");
} else {
console.log("Access denied.");
}
Output:
You can access the management panel.
Using the NOT Operator (!)
The ! operator reverses a Boolean value.
let isLoggedIn = false;
if (!isLoggedIn) {
console.log("Please log in.");
}
Output:
Please log in.
7. Nested if Statements in JavaScript
A nested if statement is an if statement placed inside another if statement.
It is useful when one condition should be checked only after another condition is satisfied.
Example
let age = 22;
let hasID = true;
if (age >= 18) {
if (hasID) {
console.log("Entry allowed.");
} else {
console.log("Please show your ID.");
}
} else {
console.log("Entry not allowed.");
}
Output:
Entry allowed.
First, JavaScript checks the age. If the age is at least 18, it then checks whether the person has an ID.
Avoid deeply nested conditions when possible because they can make your code difficult to read.
8. Common Mistakes to Avoid
Mistake 1: Using = Instead of ===
Incorrect:
let age = 18;
if (age = 20) {
console.log("Age is 20");
}
Here, = assigns a value instead of comparing two values. Since 20 is truthy, the condition passes.
Correct:
let age = 18;
if (age === 20) {
console.log("Age is 20");
}
This code checks whether age is exactly equal to 20.
Mistake 2: Forgetting Curly Braces
JavaScript allows a single statement without curly braces, but using braces consistently makes code easier to maintain.
Recommended:
if (age >= 18) {
console.log("Adult");
}
Mistake 3: Incorrect Condition Order
Incorrect:
let marks = 85;
if (marks >= 40) {
console.log("Pass");
} else if (marks >= 80) {
console.log("Excellent");
}
Output:
Pass
The second condition is never reached because the first condition is already true.
Correct:
let marks = 85;
if (marks >= 80) {
console.log("Excellent");
} else if (marks >= 40) {
console.log("Pass");
} else {
console.log("Fail");
}
Output:
Excellent
Mistake 4: Using Separate if Statements When You Need One Decision
Consider this example:
let marks = 85;
if (marks >= 40) {
console.log("Pass");
}
if (marks >= 80) {
console.log("Excellent");
}
Output:
Pass
Excellent
Both blocks execute because they are independent if statements.
If you want only one matching result, use an if...else if...else chain.
9. Difference Between if…else and the Ternary Operator
For simple conditions, JavaScript also provides the ternary operator (? :).
Using if...else:
let age = 20;
let message;
if (age >= 18) {
message = "Adult";
} else {
message = "Minor";
}
console.log(message);
Using the ternary operator:
let age = 20;
let message = age >= 18 ? "Adult" : "Minor";
console.log(message);
Both examples produce:
Adult
Use if...else for more complex logic and the ternary operator for short, simple choices.
10. Best Practices for Using Conditional Statements
Follow these practices to write cleaner JavaScript code:
- Use
===for strict equality comparisons in most cases. - Keep conditions simple and easy to understand.
- Order conditions carefully, especially when checking ranges.
- Use curly braces around blocks for better readability.
- Avoid unnecessary nested
ifstatements. - Use
else ifwhen only one branch should execute. - Consider early returns when working with functions to reduce nesting.
11. Practice Exercises
Try solving these exercises to improve your understanding of JavaScript conditional statements.
Exercise 1: Write a program that checks whether a person is eligible to vote. Use an age of 18 as the minimum.
Exercise 2: Write a program that checks whether a number is positive, negative, or zero.
Exercise 3: Write a program that assigns grades based on marks:
- 90 or above: Grade A
- 75 to 89: Grade B
- 50 to 74: Grade C
- Below 50: Fail
Exercise 4: Write a program that checks whether a user can access an admin panel based on an isAdmin Boolean variable.
Exercise 5: Write a program that applies a discount based on the purchase amount:
- ₹5,000 or more: 20% discount
- ₹2,000 or more: 10% discount
- Below ₹2,000: No discount
Try writing the code before checking your answers in a JavaScript console or browser developer tools.
Frequently Asked Questions (FAQs)
1. What is an if statement in JavaScript?
An if statement executes a block of code when its condition evaluates to true.
2. What is the difference between if and else?
The if statement runs when its condition is true. The else statement runs when the if condition is false.
3. When should I use else if in JavaScript?
Use else if when you need to check multiple conditions and execute only the first matching branch.
4. Can I use multiple else if statements?
Yes. You can use multiple else if statements between an if statement and an optional else statement.
5. Can I use an if statement without else?
Yes. The else statement is optional. If the condition is false, JavaScript simply skips the if block.
6. What happens if multiple conditions are true?
In an if...else if...else chain, JavaScript executes only the first branch whose condition is true. With separate if statements, multiple blocks can execute.
7. What is the difference between else if and multiple if statements?
An else if chain stops after the first true condition. Separate if statements are checked independently, so more than one block can execute.
Conclusion
JavaScript conditional statements are an important part of programming. The if statement checks a condition, else if lets you check additional conditions, and else handles the remaining cases.
You can use these statements to validate user input, check login status, assign grades, calculate discounts, and control application behavior.
Practice these examples and exercises to build a strong foundation before moving on to other JavaScript topics, such as the switch statement and loops.