JavaScript If-Else Statement

If-Else Statement Basics

The if-else statement is the fundamental building block of conditional logic in JavaScript. It allows your program to make decisions and execute different code blocks based on whether conditions are true or false.

javascript
1// Basic if-else statement structure
2let temperature = 25;
3
4if (temperature > 30) {
5    console.log("It's hot outside");
6} else if (temperature > 20) {
7    console.log("It's warm outside");  // This will execute
8} else {
9    console.log("It's cold outside");
10}
11
12// Code execution flow explanation:
13// 1. Check if temperature > 30 → false
14// 2. Move to else-if, check if temperature > 20 → true
15// 3. Execute the code block: console.log("It's warm outside")
16// 4. Skip the else block
17
18console.log("Program continues..."); // This always executes

If-Else Core Components

  • Condition Evaluation - JavaScript evaluates conditions as true or false
  • Code Blocks - Curly braces {} define blocks of code to execute
  • Sequential Checking - Conditions are checked from top to bottom
  • Single Execution - Only one block executes - first condition that passes

If-Else Syntax and Structure

Understanding the complete syntax of if-else statements is crucial for writing effective conditional logic. The structure includes if, optional else-if chains, and optional else clauses.

javascript
1// Complete if-else syntax breakdown
2
3// 1. Simple if statement (no else)
4let age = 18;
5if (age >= 18) {
6    console.log("You are an adult");
7}
8
9// 2. If-else statement (two alternatives)
10let score = 85;
11if (score >= 60) {
12    console.log("You passed the exam");
13} else {
14    console.log("You failed the exam");
15}
16
17// 3. If-else if-else statement (multiple conditions)
18let time = 14; // 2 PM
19if (time < 12) {
20    console.log("Good morning");
21} else if (time < 18) {
22    console.log("Good afternoon"); // This executes
23} else {
24    console.log("Good evening");
25}
26
27// 4. Multiple else-if conditions
28let grade = 87;
29if (grade >= 90) {
30    console.log("Grade: A");
31} else if (grade >= 80) {
32    console.log("Grade: B"); // This executes
33} else if (grade >= 70) {
34    console.log("Grade: C");
35} else if (grade >= 60) {
36    console.log("Grade: D");
37} else {
38    console.log("Grade: F");
39}
40
41// 5. Nested if statements
42let isLoggedIn = true;
43let userRole = "admin";
44
45if (isLoggedIn) {
46    if (userRole === "admin") {
47        console.log("Welcome, Administrator");
48    } else {
49        console.log("Welcome, User");
50    }
51} else {
52    console.log("Please log in");
53}
54
55// Syntax rules:
56// - Conditions must be in parentheses ()
57// - Code blocks must be in curly braces {}
58// - else and else-if are optional
59// - Only one block executes (first true condition)

Syntax Components

  • if (condition) - Mandatory starting point, checks first condition
  • else if (condition) - Optional additional conditions to check
  • else - Optional catch-all when no conditions match
  • Code Blocks - {} contain executable code for each condition

Condition Evaluation and Truthy/Falsy

JavaScript uses truthy and falsy evaluation in conditions. Understanding what evaluates to true or false is essential for writing correct conditional logic.

javascript
1// Truthy and Falsy values in conditions
2
3// Falsy values (evaluate to false):
4if (false) {}           // false
5if (0) {}               // zero
6if (-0) {}              // negative zero
7if (0n) {}              // BigInt zero
8if ("") {}              // empty string
9if (null) {}            // null
10if (undefined) {}       // undefined
11if (NaN) {}             // Not a Number
12
13// Truthy values (evaluate to true):
14if (true) {}            // true
15if (1) {}               // any non-zero number
16if (-1) {}              // negative numbers
17if ("hello") {}         // non-empty strings
18if ([]) {}              // empty array
19if ({}) {}              // empty object
20if (function() {}) {}   // functions
21
22// Practical examples:
23let name = "Alice";
24if (name) {
25    console.log("Hello, " + name); // Executes - string is truthy
26}
27
28let count = 0;
29if (count) {
30    console.log("Count is non-zero"); // Doesn't execute - 0 is falsy
31} else {
32    console.log("Count is zero"); // Executes
33}
34
35let user = null;
36if (user) {
37    console.log("User exists"); // Doesn't execute - null is falsy
38} else {
39    console.log("No user"); // Executes
40}
41
42// Complex conditions with logical operators
43let age = 25;
44let hasLicense = true;
45
46// AND operator (&&) - both must be true
47if (age >= 18 && hasLicense) {
48    console.log("You can drive"); // Executes
49}
50
51// OR operator (||) - at least one must be true
52let isWeekend = false;
53let isHoliday = true;
54if (isWeekend || isHoliday) {
55    console.log("No work today"); // Executes
56}
57
58// NOT operator (!) - inverts the condition
59let isRaining = false;
60if (!isRaining) {
61    console.log("Let's go outside"); // Executes
62}
63
64// Combining operators
65let temperature = 22;
66let isSunny = true;
67if ((temperature > 20 && temperature < 30) && isSunny) {
68    console.log("Perfect weather for a walk"); // Executes
69}

Comparison Operators in Conditions

Comparison operators are used to compare values in conditions. Understanding the difference between == and ===, and how different operators work is crucial for accurate condition evaluation.

javascript
1// Equality operators
2let number = 5;
3let stringNumber = "5";
4
5// Loose equality (==) - checks value with type conversion
6console.log(number == 5);        // true
7console.log(number == "5");      // true (type conversion)
8console.log(0 == false);         // true (type conversion)
9console.log(null == undefined);  // true
10
11// Strict equality (===) - checks value AND type
12console.log(number === 5);       // true
13console.log(number === "5");     // false (different types)
14console.log(0 === false);        // false (different types)
15console.log(null === undefined); // false
16
17// Inequality operators
18console.log(number != 3);        // true
19console.log(number != "5");      // false (loose equality)
20console.log(number !== "5");     // true (strict equality)
21
22// Relational operators
23let a = 10, b = 5;
24
25console.log(a > b);      // true  - greater than
26console.log(a < b);      // false - less than
27console.log(a >= 10);    // true  - greater than or equal
28console.log(b <= 5);     // true  - less than or equal
29
30// String comparisons (lexicographical order)
31console.log("apple" < "banana");     // true
32console.log("apple" === "apple");    // true
33console.log("Z" > "a");             // false (ASCII values)
34
35// Special cases with null and undefined
36console.log(null == undefined);      // true
37console.log(null === undefined);     // false
38console.log(null > 0);              // false
39console.log(null == 0);             // false
40console.log(null >= 0);             // true (null becomes 0)
41
42// Practical usage in conditions
43let userAge = 25;
44let userName = "John";
45
46// Multiple conditions
47if (userAge >= 18 && userAge <= 65) {
48    console.log("Working age");
49}
50
51// String conditions
52if (userName === "John" || userName === "Jane") {
53    console.log("Hello, John or Jane");
54}
55
56// Range checking
57let score = 85;
58if (score >= 90) {
59    console.log("Excellent");
60} else if (score >= 80) {
61    console.log("Good"); // Executes
62} else if (score >= 70) {
63    console.log("Average");
64} else {
65    console.log("Needs improvement");
66}
67
68// Best practice: Always use === instead of ==
69let input = "0";
70if (input === 0) {
71    console.log("This won't execute");
72} else if (input == 0) {
73    console.log("This will execute (type coercion)");
74}

Advanced If-Else Patterns

Beyond basic if-else statements, there are advanced patterns and techniques that make conditional logic more efficient, readable, and maintainable.

javascript
1// Pattern 1: Early returns (avoid deep nesting)
2function processUser(user) {
3    // Early return for invalid cases
4    if (!user) {
5        return "No user provided";
6    }
7    
8    if (!user.email) {
9        return "User email is required";
10    }
11    
12    if (user.age < 18) {
13        return "User must be 18 or older";
14    }
15    
16    // Main logic (no deep nesting)
17    return `Welcome, ${user.name}!`;
18}
19
20// Pattern 2: Guard clauses
21function calculateDiscount(price, isMember, couponCode) {
22    // Guard clauses for edge cases
23    if (price <= 0) return 0;
24    if (!isMember && !couponCode) return 0;
25    
26    // Main discount logic
27    let discount = 0;
28    if (isMember) discount += 10;
29    if (couponCode === "SAVE20") discount += 20;
30    
31    return Math.min(discount, 50); // Max 50% discount
32}
33
34// Pattern 3: Conditional variable assignment
35let userStatus = "offline";
36let message = userStatus === "online" ? "User is available" : "User is offline";
37
38// Equivalent to:
39// let message;
40// if (userStatus === "online") {
41//     message = "User is available";
42// } else {
43//     message = "User is offline";
44// }
45
46// Pattern 4: Switch-like behavior with if-else
47let day = "monday";
48if (day === "monday" || day === "tuesday" || day === "wednesday") {
49    console.log("Weekday");
50} else if (day === "thursday" || day === "friday") {
51    console.log("Almost weekend");
52} else if (day === "saturday" || day === "sunday") {
53    console.log("Weekend");
54} else {
55    console.log("Invalid day");
56}
57
58// Pattern 5: Object lookup (alternative to long if-else chains)
59const statusMessages = {
60    pending: "Your request is being processed",
61    approved: "Your request has been approved",
62    rejected: "Your request has been rejected",
63    default: "Unknown status"
64};
65
66let status = "approved";
67console.log(statusMessages[status] || statusMessages.default);
68
69// Pattern 6: Multiple conditions with arrays
70let favoriteFruits = ["apple", "banana", "orange"];
71let selectedFruit = "banana";
72
73if (favoriteFruits.includes(selectedFruit)) {
74    console.log("This is one of your favorite fruits!");
75}
76
77// Pattern 7: Short-circuit evaluation
78let user = { name: "Alice" };
79let displayName = user && user.name ? user.name : "Anonymous";
80
81// Pattern 8: Complex logical conditions
82let hasSubscription = true;
83let trialDaysLeft = 5;
84let paymentMethod = "credit_card";
85
86if ((hasSubscription || trialDaysLeft > 0) && paymentMethod) {
87    console.log("Access granted");
88}
89
90// Pattern 9: Nested conditions with clear structure
91let weather = "sunny";
92let temperature = 25;
93
94if (weather === "sunny") {
95    if (temperature > 30) {
96        console.log("Go to the beach");
97    } else if (temperature > 20) {
98        console.log("Perfect for a picnic");
99    } else {
100        console.log("Enjoy the sunshine");
101    }
102} else if (weather === "rainy") {
103    console.log("Stay indoors");
104}

Common If-Else Mistakes and Pitfalls

Understanding common mistakes in if-else statements helps you write more robust and bug-free code. These pitfalls often lead to unexpected behavior and hard-to-find bugs.

javascript
1// Mistake 1: Using assignment (=) instead of comparison (==/===)
2let count = 5;
3
4// WRONG - this assigns 10 to count, always evaluates to true
5if (count = 10) {
6    console.log("Count is 10"); // Always executes!
7}
8
9// CORRECT - use comparison operator
10if (count === 10) {
11    console.log("Count is 10");
12}
13
14// Mistake 2: Incorrect operator precedence
15let a = 5, b = 10, c = 15;
16
17// WRONG - && has higher precedence than ||
18if (a > 0 || b > 0 && c > 0) {
19    console.log("This might not do what you expect");
20}
21
22// CORRECT - use parentheses for clarity
23if ((a > 0 || b > 0) && c > 0) {
24    console.log("Clear intent");
25}
26
27// Mistake 3: Floating point comparisons
28let price = 0.1 + 0.2; // 0.30000000000000004
29
30// WRONG - floating point precision issues
31if (price === 0.3) {
32    console.log("This might not execute");
33}
34
35// CORRECT - use tolerance for floating point
36if (Math.abs(price - 0.3) < 0.0001) {
37    console.log("Price is approximately 0.3");
38}
39
40// Mistake 4: Forgetting braces (causes unexpected behavior)
41let isAdmin = true;
42
43// WRONG - without braces, only first statement is conditional
44if (isAdmin)
45    console.log("Welcome admin");
46    console.log("You have special privileges"); // This ALWAYS executes!
47
48// CORRECT - always use braces
49if (isAdmin) {
50    console.log("Welcome admin");
51    console.log("You have special privileges");
52}
53
54// Mistake 5: Overly complex conditions
55// WRONG - hard to read and maintain
56if ((user.role === 'admin' || user.role === 'moderator') && (user.isActive || user.lastLogin > Date.now() - 86400000) && !user.isBanned) {
57    console.log("Access granted");
58}
59
60// CORRECT - break into variables or functions
61const hasValidRole = user.role === 'admin' || user.role === 'moderator';
62const isRecentlyActive = user.isActive || user.lastLogin > Date.now() - 86400000;
63const isNotBanned = !user.isBanned;
64
65if (hasValidRole && isRecentlyActive && isNotBanned) {
66    console.log("Access granted");
67}
68
69// Mistake 6: Incorrect else-if ordering
70let score = 95;
71
72// WRONG - conditions in wrong order
73if (score > 60) {
74    console.log("Pass"); // This executes, but we miss the A grade
75} else if (score > 90) {
76    console.log("Grade: A"); // Never reached!
77}
78
79// CORRECT - check most specific conditions first
80if (score > 90) {
81    console.log("Grade: A"); // This executes
82} else if (score > 60) {
83    console.log("Pass");
84}
85
86// Mistake 7: Not considering all edge cases
87function getPriceLabel(price) {
88    // WRONG - doesn't handle negative prices
89    if (price > 100) {
90        return "Expensive";
91    } else if (price > 50) {
92        return "Moderate";
93    } else {
94        return "Cheap"; // This would return for negative prices!
95    }
96}
97
98// CORRECT - handle edge cases explicitly
99function getPriceLabelCorrect(price) {
100    if (price < 0) {
101        return "Invalid price";
102    } else if (price > 100) {
103        return "Expensive";
104    } else if (price > 50) {
105        return "Moderate";
106    } else {
107        return "Cheap";
108    }
109}

If-Else Best Practices

Following established best practices for if-else statements leads to more readable, maintainable, and bug-free code. These guidelines help you write clean conditional logic.

javascript
1// Best Practice 1: Always use curly braces, even for single statements
2let temperature = 25;
3
4// GOOD - consistent and safe
5if (temperature > 30) {
6    console.log("It's hot");
7} else {
8    console.log("It's not hot");
9}
10
11// AVOID - prone to errors when adding more statements
12// if (temperature > 30)
13//     console.log("It's hot");
14
15// Best Practice 2: Use strict equality (===) instead of loose equality (==)
16let count = "5";
17
18// GOOD - explicit and predictable
19if (count === 5) {
20    console.log("Count is exactly 5 (number)");
21} else if (count === "5") {
22    console.log("Count is exactly '5' (string)"); // This executes
23}
24
25// AVOID - unexpected type coercion
26// if (count == 5) {
27//     console.log("This might execute unexpectedly");
28// }
29
30// Best Practice 3: Keep conditions simple and readable
31const user = { age: 25, isVerified: true, balance: 100 };
32
33// GOOD - break complex conditions into variables
34const isEligibleForLoan = user.age >= 18 && user.isVerified && user.balance > 0;
35const hasGoodCredit = user.balance > 50;
36
37if (isEligibleForLoan && hasGoodCredit) {
38    console.log("Loan approved");
39}
40
41// Best Practice 4: Use positive conditions when possible
42const isUserLoggedIn = true;
43
44// GOOD - positive conditions are easier to understand
45if (isUserLoggedIn) {
46    console.log("Welcome back!");
47} else {
48    console.log("Please log in");
49}
50
51// AVOID - double negatives are confusing
52// if (!isUserLoggedIn === false) {
53//     console.log("This is hard to read");
54// }
55
56// Best Practice 5: Use early returns to avoid deep nesting
57function processOrder(order) {
58    // Early returns for invalid cases
59    if (!order) return "No order provided";
60    if (!order.items || order.items.length === 0) return "Order is empty";
61    if (order.total <= 0) return "Invalid order total";
62    
63    // Main logic (no nesting)
64    return `Processing order with ${order.items.length} items`;
65}
66
67// Best Practice 6: Order conditions from most specific to most general
68let score = 95;
69
70// GOOD - specific conditions first
71if (score >= 90) {
72    console.log("Grade: A");
73} else if (score >= 80) {
74    console.log("Grade: B");
75} else if (score >= 70) {
76    console.log("Grade: C");
77} else {
78    console.log("Grade: F");
79}
80
81// Best Practice 7: Use descriptive condition variables
82const userAge = 25;
83const hasDriversLicense = true;
84const hasCarInsurance = true;
85
86// GOOD - conditions are self-documenting
87const canDrive = userAge >= 16 && hasDriversLicense;
88const isFullyInsured = hasDriversLicense && hasCarInsurance;
89
90if (canDrive && isFullyInsured) {
91    console.log("You can drive legally");
92}
93
94// Best Practice 8: Consider alternative patterns for long if-else chains
95const status = "pending";
96
97// For long chains, consider switch or object lookup
98const statusHandlers = {
99    pending: () => console.log("Processing..."),
100    approved: () => console.log("Approved!"),
101    rejected: () => console.log("Rejected"),
102};
103
104if (statusHandlers[status]) {
105    statusHandlers[status]();
106} else {
107    console.log("Unknown status");
108}
109
110// Best Practice 9: Use parentheses for complex conditions
111const isWeekend = true;
112const isHoliday = false;
113const hasVacationDays = true;
114
115// GOOD - parentheses make precedence clear
116if ((isWeekend || isHoliday) && hasVacationDays) {
117    console.log("Time to relax!");
118}
119
120// Best Practice 10: Write tests for your conditions
121function canVote(age, isCitizen, hasId) {
122    return age >= 18 && isCitizen && hasId;
123}
124
125// Test cases
126console.log(canVote(25, true, true));  // true
127console.log(canVote(17, true, true));  // false
128console.log(canVote(25, false, true)); // false
129console.log(canVote(25, true, false)); // false

JavaScript If-Else FAQ

What is the basic syntax of an if-else statement?

The basic syntax is: if (condition) { code } else { code }. You can add multiple else-if conditions: if (cond1) { code } else if (cond2) { code } else { code }. Conditions are evaluated from top to bottom, and only the first true condition executes.

What's the difference between == and === in conditions?

== performs loose equality with type coercion ("5" == 5 is true), while === performs strict equality checking both value and type ("5" === 5 is false). Always use === to avoid unexpected type conversions.

Can I have multiple else-if conditions?

Yes, you can have as many else-if conditions as needed. However, if you have more than 3-4 else-if conditions, consider using a switch statement or object lookup for better readability.

What happens if no conditions are true and there's no else block?

If no conditions evaluate to true and there's no else block, the entire if-else statement is skipped, and execution continues with the next line of code after the statement.

Can I nest if statements inside other if statements?

Yes, you can nest if statements arbitrarily deep. However, deeply nested code can be hard to read and maintain. Consider using early returns or breaking complex logic into separate functions.

What are truthy and falsy values in JavaScript?

Falsy values: false, 0, -0, 0n, "", null, undefined, NaN. All other values are truthy. In conditions, JavaScript automatically converts values to boolean using these rules.

Should I always use curly braces for single statements?

Yes, always use curly braces even for single statements. This prevents bugs when adding more statements later and makes the code more consistent and readable.

What's the difference between if-else and the ternary operator?

if-else is a statement used for control flow, while the ternary operator (condition ? expr1 : expr2) is an expression that returns a value. Use if-else for executing code blocks and ternary for simple value assignments.

How can I avoid deeply nested if-else statements?

Use early returns, break complex conditions into variables, use guard clauses, consider switch statements for multiple discrete values, or use object lookups for mapping values to actions.

What's the performance impact of long if-else chains?

JavaScript engines optimize if-else chains efficiently. However, for very long chains (10+ conditions), consider ordering conditions by likelihood (most common first) or using alternative patterns like object lookups for better performance and maintainability.