How to write if, else if, and else statements in JavaScript
How to Write if, else if, and else Statements in JavaScript
Table of Contents
1. [Introduction](#introduction)
2. [Prerequisites](#prerequisites)
3. [Understanding Conditional Logic](#understanding-conditional-logic)
4. [Basic if Statement Syntax](#basic-if-statement-syntax)
5. [The else Statement](#the-else-statement)
6. [The else if Statement](#the-else-if-statement)
7. [Comparison Operators](#comparison-operators)
8. [Logical Operators](#logical-operators)
9. [Practical Examples and Use Cases](#practical-examples-and-use-cases)
10. [Advanced Conditional Patterns](#advanced-conditional-patterns)
11. [Common Mistakes and Troubleshooting](#common-mistakes-and-troubleshooting)
12. [Best Practices](#best-practices)
13. [Performance Considerations](#performance-considerations)
14. [Alternative Conditional Approaches](#alternative-conditional-approaches)
15. [Conclusion](#conclusion)
Introduction
Conditional statements are fundamental building blocks in JavaScript programming that allow your code to make decisions based on different conditions. The `if`, `else if`, and `else` statements form the backbone of decision-making logic in JavaScript applications, enabling developers to create dynamic, responsive programs that can handle various scenarios and user inputs.
In this comprehensive guide, you'll learn everything you need to know about writing conditional statements in JavaScript, from basic syntax to advanced patterns and best practices. Whether you're a beginner just starting your programming journey or an experienced developer looking to refine your conditional logic skills, this article will provide you with practical examples, real-world use cases, and expert insights to master JavaScript conditionals.
By the end of this guide, you'll understand how to:
- Write basic if statements with proper syntax
- Implement else and else if clauses effectively
- Use comparison and logical operators in conditions
- Handle complex conditional scenarios
- Avoid common pitfalls and debugging issues
- Apply best practices for clean, maintainable code
Prerequisites
Before diving into JavaScript conditional statements, you should have:
- Basic understanding of JavaScript syntax and variables
- Familiarity with data types (strings, numbers, booleans)
- Knowledge of how to run JavaScript code (browser console, Node.js, or code editor)
- Understanding of basic programming concepts like expressions and statements
Understanding Conditional Logic
Conditional logic allows programs to execute different code blocks based on whether specific conditions are true or false. In JavaScript, conditions are evaluated as boolean values (`true` or `false`), and the program flow changes accordingly.
The fundamental concept behind conditional statements is:
- If a condition is true, execute a specific block of code
- Else if another condition is true, execute a different block of code
- Else (if none of the above conditions are true), execute a default block of code
Basic if Statement Syntax
The `if` statement is the most basic form of conditional logic in JavaScript. It executes a block of code only when a specified condition evaluates to `true`.
Syntax Structure
```javascript
if (condition) {
// Code to execute if condition is true
}
```
Simple if Statement Example
```javascript
let temperature = 25;
if (temperature > 20) {
console.log("It's a warm day!");
}
// Output: "It's a warm day!"
```
Single Line if Statement
For simple statements, you can omit the curly braces:
```javascript
let age = 18;
if (age >= 18) console.log("You are an adult");
```
However, using curly braces is recommended for better readability and maintainability.
Multiple Statements in if Block
```javascript
let score = 85;
if (score >= 80) {
console.log("Excellent work!");
console.log("You passed with distinction");
let bonus = score * 0.1;
console.log(`Bonus points: ${bonus}`);
}
```
The else Statement
The `else` statement provides an alternative code block that executes when the `if` condition evaluates to `false`.
Syntax Structure
```javascript
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
```
Basic else Example
```javascript
let weather = "rainy";
if (weather === "sunny") {
console.log("Let's go to the beach!");
} else {
console.log("Let's stay indoors and read a book.");
}
// Output: "Let's stay indoors and read a book."
```
Practical else Statement Example
```javascript
function checkAccountBalance(balance) {
if (balance > 0) {
console.log(`Your account balance is $${balance}`);
console.log("You can make purchases");
} else {
console.log("Insufficient funds");
console.log("Please deposit money to continue");
}
}
checkAccountBalance(150); // Positive balance message
checkAccountBalance(-50); // Insufficient funds message
```
The else if Statement
The `else if` statement allows you to test multiple conditions in sequence. It's evaluated only if the previous `if` or `else if` conditions were false.
Syntax Structure
```javascript
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else if (condition3) {
// Code for condition3
} else {
// Default code if none of the conditions are true
}
```
Basic else if Example
```javascript
let grade = 87;
if (grade >= 90) {
console.log("Grade: A");
} else if (grade >= 80) {
console.log("Grade: B");
} else if (grade >= 70) {
console.log("Grade: C");
} else if (grade >= 60) {
console.log("Grade: D");
} else {
console.log("Grade: F");
}
// Output: "Grade: B"
```
Complex else if Chain
```javascript
function determineShippingCost(weight, distance, priority) {
let cost = 0;
if (weight <= 1 && distance <= 100) {
cost = 5;
} else if (weight <= 1 && distance <= 500) {
cost = 10;
} else if (weight <= 5 && distance <= 100) {
cost = 15;
} else if (weight <= 5 && distance <= 500) {
cost = 25;
} else if (weight > 5) {
cost = 50;
} else {
cost = 30; // Default for other cases
}
if (priority === "express") {
cost *= 1.5;
}
return cost;
}
console.log(determineShippingCost(2, 150, "standard")); // 15
console.log(determineShippingCost(2, 150, "express")); // 22.5
```
Comparison Operators
Comparison operators are essential for creating conditions in if statements. They compare two values and return a boolean result.
Common Comparison Operators
| Operator | Description | Example |
|----------|-------------|---------|
| `==` | Equal to (loose equality) | `5 == "5"` → `true` |
| `===` | Strict equal to | `5 === "5"` → `false` |
| `!=` | Not equal to (loose inequality) | `5 != "3"` → `true` |
| `!==` | Strict not equal to | `5 !== "5"` → `true` |
| `>` | Greater than | `10 > 5` → `true` |
| `<` | Less than | `3 < 8` → `true` |
| `>=` | Greater than or equal to | `5 >= 5` → `true` |
| `<=` | Less than or equal to | `4 <= 7` → `true` |
Comparison Examples
```javascript
let userAge = 25;
let requiredAge = 21;
// Strict equality (recommended)
if (userAge === requiredAge) {
console.log("Exact age match");
}
// Greater than comparison
if (userAge > requiredAge) {
console.log("User is older than required");
}
// String comparison
let userName = "Alice";
if (userName === "Alice") {
console.log("Welcome back, Alice!");
}
// Loose vs strict equality
let numberString = "42";
let numberValue = 42;
if (numberString == numberValue) {
console.log("Loose equality: true");
}
if (numberString === numberValue) {
console.log("This won't execute - strict equality: false");
}
```
Logical Operators
Logical operators allow you to combine multiple conditions in a single if statement.
Logical Operator Types
| Operator | Description | Example |
|----------|-------------|---------|
| `&&` | AND - all conditions must be true | `(a > 5) && (b < 10)` |
| `\|\|` | OR - at least one condition must be true | `(a === 1) \|\| (b === 2)` |
| `!` | NOT - inverts the boolean value | `!(a > 5)` |
Logical Operator Examples
```javascript
let age = 25;
let hasLicense = true;
let hasInsurance = true;
// AND operator - all conditions must be true
if (age >= 18 && hasLicense && hasInsurance) {
console.log("You can rent a car");
}
// OR operator - at least one condition must be true
let isWeekend = false;
let isHoliday = true;
if (isWeekend || isHoliday) {
console.log("No work today!");
}
// NOT operator - inverts the condition
let isLoggedIn = false;
if (!isLoggedIn) {
console.log("Please log in to continue");
}
// Complex logical combinations
let temperature = 22;
let humidity = 60;
let isRaining = false;
if ((temperature > 20 && temperature < 30) && humidity < 70 && !isRaining) {
console.log("Perfect weather for outdoor activities!");
}
```
Short-Circuit Evaluation
JavaScript uses short-circuit evaluation with logical operators:
```javascript
let user = null;
// Short-circuit with AND - prevents error if user is null
if (user && user.isAdmin) {
console.log("Admin access granted");
}
// Short-circuit with OR - provides default value
let userName = user && user.name || "Guest";
console.log(`Welcome, ${userName}!`);
```
Practical Examples and Use Cases
User Authentication System
```javascript
function authenticateUser(username, password, isActive, attempts) {
if (!username || !password) {
return "Username and password are required";
} else if (attempts >= 3) {
return "Account locked due to too many failed attempts";
} else if (!isActive) {
return "Account is deactivated";
} else if (username === "admin" && password === "secure123") {
return "Admin login successful";
} else if (username === "user" && password === "password") {
return "User login successful";
} else {
return "Invalid credentials";
}
}
// Test cases
console.log(authenticateUser("", "password", true, 0));
// "Username and password are required"
console.log(authenticateUser("admin", "secure123", true, 0));
// "Admin login successful"
console.log(authenticateUser("user", "wrong", true, 3));
// "Account locked due to too many failed attempts"
```
E-commerce Discount Calculator
```javascript
function calculateDiscount(customerType, orderAmount, isFirstOrder, promoCode) {
let discount = 0;
let discountReason = "";
if (customerType === "premium" && orderAmount >= 100) {
discount = 0.20; // 20% discount
discountReason = "Premium customer discount";
} else if (customerType === "regular" && orderAmount >= 200) {
discount = 0.15; // 15% discount
discountReason = "High value order discount";
} else if (isFirstOrder && orderAmount >= 50) {
discount = 0.10; // 10% discount
discountReason = "First-time customer discount";
} else if (promoCode === "SAVE10" && orderAmount >= 75) {
discount = 0.10; // 10% discount
discountReason = "Promo code discount";
} else if (orderAmount >= 300) {
discount = 0.05; // 5% discount
discountReason = "Large order discount";
}
let discountAmount = orderAmount * discount;
let finalAmount = orderAmount - discountAmount;
return {
originalAmount: orderAmount,
discountPercentage: discount * 100,
discountAmount: discountAmount,
finalAmount: finalAmount,
reason: discountReason || "No discount applied"
};
}
// Example usage
console.log(calculateDiscount("premium", 150, false, ""));
// Premium customer gets 20% discount on $150 order
```
Form Validation System
```javascript
function validateRegistrationForm(userData) {
const { email, password, confirmPassword, age, termsAccepted } = userData;
let errors = [];
// Email validation
if (!email) {
errors.push("Email is required");
} else if (!email.includes("@") || !email.includes(".")) {
errors.push("Please enter a valid email address");
}
// Password validation
if (!password) {
errors.push("Password is required");
} else if (password.length < 8) {
errors.push("Password must be at least 8 characters long");
} else if (!/[A-Z]/.test(password)) {
errors.push("Password must contain at least one uppercase letter");
} else if (!/[0-9]/.test(password)) {
errors.push("Password must contain at least one number");
}
// Confirm password validation
if (password !== confirmPassword) {
errors.push("Passwords do not match");
}
// Age validation
if (!age) {
errors.push("Age is required");
} else if (age < 13) {
errors.push("You must be at least 13 years old to register");
} else if (age > 120) {
errors.push("Please enter a valid age");
}
// Terms validation
if (!termsAccepted) {
errors.push("You must accept the terms and conditions");
}
return {
isValid: errors.length === 0,
errors: errors
};
}
// Example usage
const formData = {
email: "user@example.com",
password: "SecurePass123",
confirmPassword: "SecurePass123",
age: 25,
termsAccepted: true
};
const validation = validateRegistrationForm(formData);
console.log(validation); // { isValid: true, errors: [] }
```
Advanced Conditional Patterns
Nested Conditional Statements
```javascript
function processLoanApplication(creditScore, income, employmentYears, loanAmount) {
if (creditScore >= 700) {
if (income >= 50000) {
if (employmentYears >= 2) {
if (loanAmount <= income * 4) {
return "Loan approved at standard rate";
} else {
return "Loan amount too high for income";
}
} else {
return "Insufficient employment history";
}
} else if (income >= 30000 && employmentYears >= 5) {
return "Loan approved at higher rate";
} else {
return "Income too low for loan approval";
}
} else if (creditScore >= 600) {
if (income >= 60000 && employmentYears >= 3) {
return "Loan approved with co-signer required";
} else {
return "Loan denied - improve credit score";
}
} else {
return "Loan denied - credit score too low";
}
}
```
Conditional Assignment Patterns
```javascript
// Ternary operator for simple conditions
let userRole = isAdmin ? "administrator" : "user";
// Multiple ternary operators (use sparingly)
let accessLevel = userRole === "admin" ? "full" :
userRole === "moderator" ? "limited" : "read-only";
// Conditional assignment with logical operators
let displayName = user.firstName || user.email || "Anonymous";
// Complex conditional assignment
function getUserPermissions(user) {
let permissions = [];
if (user.role === "admin") {
permissions = ["read", "write", "delete", "manage"];
} else if (user.role === "editor") {
permissions = ["read", "write"];
if (user.department === "content") {
permissions.push("publish");
}
} else if (user.role === "viewer") {
permissions = ["read"];
if (user.isPremium) {
permissions.push("download");
}
}
return permissions;
}
```
Common Mistakes and Troubleshooting
Assignment vs Equality Comparison
```javascript
// WRONG - Assignment instead of comparison
let x = 10;
if (x = 5) { // This assigns 5 to x, doesn't compare
console.log("This will always execute");
}
// CORRECT - Comparison
if (x === 5) {
console.log("x equals 5");
}
```
Truthy and Falsy Values
Understanding JavaScript's truthy and falsy values is crucial:
```javascript
// Falsy values: false, 0, "", null, undefined, NaN
let emptyString = "";
let zero = 0;
let nullValue = null;
if (emptyString) {
console.log("This won't execute");
}
if (zero) {
console.log("This won't execute");
}
// Common mistake with arrays and objects
let emptyArray = [];
let emptyObject = {};
if (emptyArray) {
console.log("This WILL execute - arrays are truthy even when empty");
}
// Correct way to check for empty arrays
if (emptyArray.length > 0) {
console.log("Array has elements");
}
// Correct way to check for empty objects
if (Object.keys(emptyObject).length > 0) {
console.log("Object has properties");
}
```
Type Coercion Issues
```javascript
// Unexpected behavior with loose equality
console.log(0 == false); // true
console.log("" == false); // true
console.log(null == undefined); // true
console.log("0" == false); // true
// Always use strict equality
console.log(0 === false); // false
console.log("" === false); // false
console.log(null === undefined); // false
console.log("0" === false); // false
```
Missing Braces and Scope Issues
```javascript
// Dangerous - missing braces
if (condition)
console.log("First statement");
console.log("This always executes!"); // Not part of if statement
// Correct - with braces
if (condition) {
console.log("First statement");
console.log("This only executes if condition is true");
}
```
Debugging Conditional Logic
```javascript
function debugConditionals(value) {
console.log(`Input value: ${value}`);
console.log(`Type: ${typeof value}`);
console.log(`Truthy: ${!!value}`);
if (value) {
console.log("Condition evaluated as true");
} else {
console.log("Condition evaluated as false");
}
}
// Test with different values
debugConditionals(0); // falsy
debugConditionals(""); // falsy
debugConditionals("0"); // truthy
debugConditionals([]); // truthy
debugConditionals(null); // falsy
```
Best Practices
1. Use Strict Equality
Always prefer `===` and `!==` over `==` and `!=`:
```javascript
// Good
if (userInput === "yes") {
processConfirmation();
}
// Avoid
if (userInput == "yes") {
processConfirmation();
}
```
2. Keep Conditions Simple and Readable
```javascript
// Good - clear and readable
if (user.isActive && user.hasPermission("read") && !user.isBanned) {
allowAccess();
}
// Better - extract to meaningful variables
const canAccess = user.isActive && user.hasPermission("read") && !user.isBanned;
if (canAccess) {
allowAccess();
}
// Even better - extract to function
function userCanAccess(user) {
return user.isActive &&
user.hasPermission("read") &&
!user.isBanned;
}
if (userCanAccess(user)) {
allowAccess();
}
```
3. Use Early Returns to Reduce Nesting
```javascript
// Avoid deep nesting
function processOrder(order) {
if (order.isValid) {
if (order.isPaid) {
if (order.inStock) {
if (order.shippingAddress) {
// Process order
return "Order processed";
} else {
return "Missing shipping address";
}
} else {
return "Item out of stock";
}
} else {
return "Payment required";
}
} else {
return "Invalid order";
}
}
// Better - use early returns
function processOrder(order) {
if (!order.isValid) {
return "Invalid order";
}
if (!order.isPaid) {
return "Payment required";
}
if (!order.inStock) {
return "Item out of stock";
}
if (!order.shippingAddress) {
return "Missing shipping address";
}
// Process order
return "Order processed";
}
```
4. Use Consistent Formatting
```javascript
// Good formatting
if (condition) {
doSomething();
} else if (anotherCondition) {
doSomethingElse();
} else {
doDefault();
}
// Consistent indentation for complex conditions
if (
user.isAuthenticated &&
user.hasRole('admin') &&
!user.isLocked
) {
grantAdminAccess();
}
```
5. Handle Edge Cases
```javascript
function calculateAge(birthDate) {
// Handle edge cases first
if (!birthDate) {
throw new Error("Birth date is required");
}
if (!(birthDate instanceof Date)) {
throw new Error("Birth date must be a Date object");
}
if (birthDate > new Date()) {
throw new Error("Birth date cannot be in the future");
}
// Main logic
const today = new Date();
const age = today.getFullYear() - birthDate.getFullYear();
// Adjust for birthday not yet occurred this year
if (today.getMonth() < birthDate.getMonth() ||
(today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())) {
return age - 1;
}
return age;
}
```
Performance Considerations
1. Order Conditions by Likelihood
```javascript
// Put most likely conditions first
function categorizeUser(user) {
if (user.type === "regular") { // Most common case first
return "standard";
} else if (user.type === "premium") { // Second most common
return "enhanced";
} else if (user.type === "admin") { // Least common
return "administrative";
} else {
return "unknown";
}
}
```
2. Avoid Expensive Operations in Conditions
```javascript
// Avoid - expensive operation called multiple times
function processData(data) {
if (calculateComplexScore(data) > 80) {
return "high";
} else if (calculateComplexScore(data) > 60) {
return "medium";
} else if (calculateComplexScore(data) > 40) {
return "low";
}
return "very low";
}
// Better - calculate once and store
function processData(data) {
const score = calculateComplexScore(data);
if (score > 80) {
return "high";
} else if (score > 60) {
return "medium";
} else if (score > 40) {
return "low";
}
return "very low";
}
```
3. Use Short-Circuit Evaluation
```javascript
// Efficient - second condition only checked if first is true
if (user && user.preferences && user.preferences.notifications) {
sendNotification();
}
// Efficient - expensive check only if necessary
if (isBasicValidation() && isComplexValidation()) {
processForm();
}
```
Alternative Conditional Approaches
Switch Statements
For multiple discrete values, consider switch statements:
```javascript
function getSeasonMessage(month) {
switch (month) {
case 12:
case 1:
case 2:
return "Winter";
case 3:
case 4:
case 5:
return "Spring";
case 6:
case 7:
case 8:
return "Summer";
case 9:
case 10:
case 11:
return "Fall";
default:
return "Invalid month";
}
}
// Equivalent if-else chain would be longer
function getSeasonMessageIfElse(month) {
if (month === 12 || month === 1 || month === 2) {
return "Winter";
} else if (month === 3 || month === 4 || month === 5) {
return "Spring";
} else if (month === 6 || month === 7 || month === 8) {
return "Summer";
} else if (month === 9 || month === 10 || month === 11) {
return "Fall";
} else {
return "Invalid month";
}
}
```
Object-Based Conditional Logic
```javascript
// Object lookup for simple mappings
const statusMessages = {
pending: "Your request is being processed",
approved: "Your request has been approved",
rejected: "Your request has been rejected",
cancelled: "Your request has been cancelled"
};
function getStatusMessage(status) {
return statusMessages[status] || "Unknown status";
}
// Function mapping for more complex logic
const actionHandlers = {
create: (data) => createRecord(data),
update: (data) => updateRecord(data),
delete: (data) => deleteRecord(data),
read: (data) => readRecord(data)
};
function handleAction(action, data) {
const handler = actionHandlers[action];
if (handler) {
return handler(data);
} else {
throw new Error(`Unknown action: ${action}`);
}
}
```
Ternary Operators
Use for simple conditional assignments:
```javascript
// Simple ternary
const message = isLoggedIn ? "Welcome back!" : "Please log in";
// Nested ternary (use sparingly)
const userLevel = score >= 90 ? "expert" :
score >= 70 ? "intermediate" :
score >= 50 ? "beginner" : "novice";
// Better alternative for complex conditions
function getUserLevel(score) {
if (score >= 90) return "expert";
if (score >= 70) return "intermediate";
if (score >= 50) return "beginner";
return "novice";
}
```
Conclusion
Mastering if, else if, and else statements in JavaScript is essential for creating dynamic, responsive applications. These conditional statements form the foundation of decision-making logic in your programs, allowing you to handle different scenarios, validate user input, and control program flow effectively.
Key Takeaways
1. Syntax Mastery: Understanding the proper syntax for if, else if, and else statements is fundamental to writing correct JavaScript code.
2. Comparison and Logical Operators: Knowing how to use comparison operators (`===`, `!==`, `>`, `<`) and logical operators (`&&`, `||`, `!`) effectively creates powerful conditional logic.
3. Best Practices: Always use strict equality, keep conditions simple and readable, handle edge cases, and use early returns to reduce nesting.
4. Performance Awareness: Order conditions by likelihood, avoid expensive operations in conditions, and leverage short-circuit evaluation.
5. Alternative Approaches: Consider switch statements, object-based lookups, and ternary operators for appropriate use cases.
6. Debugging Skills: Understanding truthy/falsy values, type coercion, and common pitfalls helps you write more reliable code.
Next Steps
To continue improving your JavaScript conditional logic skills:
1. Practice with Real Projects: Apply these concepts in actual applications to reinforce your understanding
2. Explore Advanced Patterns: Learn about guard clauses, strategy patterns, and functional programming approaches to conditionals
3. Study Code Reviews: Analyze how experienced developers structure their conditional logic
4. Performance Testing: Measure the performance impact of different conditional approaches in your applications
5. Error Handling: Learn how conditionals integrate with try-catch blocks and error handling strategies
Remember that clean, readable conditional logic is not just about functionality—it's about creating maintainable code that other developers (including your future self) can easily understand and modify. As you continue your JavaScript journey, these conditional statement skills will serve as building blocks for more advanced programming concepts and patterns.
By following the principles and examples outlined in this guide, you'll be well-equipped to handle any conditional logic scenario in your JavaScript applications, from simple user interface interactions to complex business logic implementations.