JavaScript tutorials  /  If-Else Statement in JavaScript
Chapter 4 · JavaScript

If-Else Statement in JavaScript

The if-else statement is a fundamental conditional control structure in JavaScript that allows a program to execute different blocks of code based on whether a specified condition evaluates to true or false.

The if-else statement lets your program make decisions. You give it a condition, and if that condition is true, one block of code runs; if it's false, a different block of code runs instead. It's how JavaScript chooses between different paths of execution based on data or user input.

Think of a traffic light system at a pedestrian crossing. If the light is green, you walk; if it's red, you stop and wait. There's no third option being evaluated at that moment, just a simple true/false decision. Similarly, in an e-commerce website, when a user tries to checkout, JavaScript code checks 'if the cart is empty', it shows a message asking the user to add items; 'else', it proceeds to the payment page. Another common example is a login form: if the entered password matches the stored password, the user is granted access; else, an 'Incorrect password' message is displayed.

The if-else statement is essential because real-world programs constantly need to make decisions based on changing data, such as user input, API responses, or calculated values. Without conditional logic, a program could only execute the same fixed sequence of instructions every time, regardless of circumstances. If-else statements allow developers to build dynamic, responsive applications that behave differently depending on conditions, such as validating form input, displaying different UI elements based on user roles, or handling different business logic based on data values.

  • Simple if Statement: Executes a block of code only if the specified condition evaluates to true. If the condition is false, the block is simply skipped, and no alternative code runs.
  • if-else Statement: Provides two possible paths of execution: the 'if' block runs when the condition is true, and the 'else' block runs when the condition is false, ensuring one of the two blocks always executes.
  • if-else if-else Ladder: Used when there are multiple conditions to check in sequence. JavaScript evaluates each 'else if' condition in order until one is true, executing its corresponding block; if none are true, the final 'else' block runs as a fallback.
  • Nested if-else Statement: An if-else statement placed inside another if or else block, used when a decision depends on multiple layers of conditions that need to be evaluated in a specific hierarchical order.
  • Ternary Operator (Conditional Expression): A shorthand, single-line alternative to a simple if-else statement, using the syntax 'condition ? expressionIfTrue : expressionIfFalse', commonly used for simple conditional assignments.
if (condition) { // code to run if condition is true } else if (anotherCondition) { // code to run if anotherCondition is true } else { // code to run if all conditions are false }
Suppose you are building a simple grading system for a school application where a student's numeric score needs to be converted into a letter grade (A, B, C, D, or F) based on specific score ranges. Without conditional logic, you would have no way to check which range the score falls into and respond accordingly. You need a way to check multiple conditions in order, such as 'is the score 90 or above', 'is the score 80 to 89', and so on, executing the appropriate block of code for whichever condition matches, using an if-else if-else ladder.
Basic if-else Statement
Demonstrates checking whether a number is even or odd using a simple if-else statement.
JavaScript
let number = 7; if (number % 2 === 0) { console.log(`${number} is even`); } else { console.log(`${number} is odd`); }
7 is odd
The condition 'number % 2 === 0' checks if the remainder of number divided by 2 is zero. Since 7 divided by 2 leaves a remainder of 1, the condition is false, so the else block executes, printing that 7 is odd.
if-else if-else Ladder for Grading System
Demonstrates evaluating multiple conditions in sequence to assign a letter grade based on a numeric score.
JavaScript
let score = 82; let grade; if (score >= 90) { grade = "A"; } else if (score >= 80) { grade = "B"; } else if (score >= 70) { grade = "C"; } else if (score >= 60) { grade = "D"; } else { grade = "F"; } console.log(`Score: ${score}, Grade: ${grade}`);
Score: 82, Grade: B
JavaScript checks each condition in order. Since score (82) is not >= 90, it moves to the next condition, score >= 80, which is true, so grade is set to 'B' and the remaining else-if and else blocks are skipped entirely.
Nested if-else for Login Validation
Demonstrates using a nested if-else statement to validate both a username and password before granting access.
JavaScript
let username = "admin"; let password = "secure123"; let inputUsername = "admin"; let inputPassword = "wrongpass"; if (inputUsername === username) { if (inputPassword === password) { console.log("Login successful"); } else { console.log("Incorrect password"); } } else { console.log("Username not found"); }
Incorrect password
The outer if checks if the username matches, which is true, so it enters the nested if-else. There, the password comparison fails, so the inner else block runs, printing 'Incorrect password'. This demonstrates how nested conditions allow multi-step validation.
Using the Ternary Operator as a Shorthand for if-else
Shows how a simple if-else statement can be rewritten as a compact ternary expression for conditional assignment.
JavaScript
let age = 20; // Traditional if-else let status; if (age >= 18) { status = "Adult"; } else { status = "Minor"; } console.log("Using if-else:", status); // Equivalent ternary operator let statusTernary = age >= 18 ? "Adult" : "Minor"; console.log("Using ternary:", statusTernary);
Using if-else: Adult Using ternary: Adult
Both approaches produce the same result. The ternary operator condensed the four-line if-else block into a single line, making it useful for simple conditional assignments where readability isn't compromised by complexity.
  • Using Assignment Operator (=) Instead of Comparison Operator (=== or ==): A very common mistake is writing 'if (x = 5)' instead of 'if (x === 5)'. The single equals sign assigns the value 5 to x and then evaluates the assignment as truthy, causing the if block to always execute regardless of the intended comparison, and silently changing the value of x.
  • Using == Instead of === for Comparisons: Using the loose equality operator (==) instead of the strict equality operator (===) can cause unexpected type coercion, such as '0 == false' or '"" == 0' both evaluating to true. This can lead to conditions passing or failing in unintended ways. Using === avoids these type coercion pitfalls.
  • Incorrect Order of Conditions in an if-else if Ladder: Placing broader or overlapping conditions before more specific ones in an if-else if ladder can cause the wrong block to execute, since JavaScript stops checking further conditions once it finds the first true one. For example, checking 'score >= 60' before 'score >= 90' would incorrectly classify a 95 as passing the 60 threshold without ever reaching the intended 90+ check.
  • Forgetting Curly Braces for Multi-Statement Blocks: Omitting curly braces {} when an if or else block is meant to contain multiple statements causes only the very next single statement to be considered part of the conditional block, while subsequent statements execute unconditionally, leading to logic errors that are hard to spot.
  • Deeply Nesting if-else Statements Unnecessarily: Excessive nesting of if-else statements (sometimes called 'pyramid of doom') makes code difficult to read and maintain. This can often be avoided by using early returns, combining conditions with logical operators (&& or ||), or using switch statements for multiple discrete value checks.
  • Always Use Strict Equality (===) for Comparisons: Prefer the strict equality operator (===) over loose equality (==) in conditional checks to avoid unexpected type coercion bugs, ensuring comparisons check both value and type.
  • Order Conditions from Most Specific to Least Specific: In an if-else if ladder, arrange conditions so that more specific or higher-priority conditions are checked first, ensuring the correct block executes before broader, catch-all conditions are reached.
  • Use Curly Braces Even for Single-Statement Blocks: Always wrap if and else blocks in curly braces {}, even when they contain only a single statement, to improve readability and prevent bugs that occur when additional statements are later added without noticing they fall outside the intended block.
  • Use Early Returns to Reduce Nesting: In functions, use early return statements to handle edge cases or invalid conditions upfront, rather than wrapping the main logic inside a deeply nested if-else structure. This flattens the code and makes the primary logic easier to follow.
  • Use the Ternary Operator Only for Simple Conditions: Reserve the ternary operator for simple, single-expression conditional assignments. For complex logic with multiple statements or nested conditions, use a full if-else block instead, since overusing ternary operators for complex logic reduces code readability.
What is the difference between if-else and a switch statement in JavaScript, and when would you use each?
An if-else statement (or if-else if ladder) is best suited for evaluating complex or range-based conditions, such as comparisons using relational operators (>, <, >=, <=) or combinations of multiple different variables. A switch statement is better suited for comparing a single variable against multiple discrete, specific values, offering cleaner syntax in that scenario. Both achieve conditional branching, but switch is generally more readable when checking many exact values of the same variable.
What will happen if you use a single equals sign (=) instead of === inside an if condition, and why is this dangerous?
Using a single equals sign inside an if condition, such as 'if (x = 5)', performs an assignment rather than a comparison. It assigns the value 5 to x and then evaluates the truthiness of that assignment (which is 5, a truthy value), so the if block executes regardless of x's original value. This is dangerous because it silently changes the value of the variable and can cause conditions to behave unpredictably, often leading to hard-to-detect bugs.
What is the difference between == and === in JavaScript conditional checks?
The == operator performs loose equality comparison, which means JavaScript will attempt type coercion before comparing values, potentially causing surprising results like '0 == false' evaluating to true. The === operator performs strict equality comparison, checking both value and type without any coercion, so '0 === false' evaluates to false. Using === is generally recommended to avoid unexpected type coercion bugs.
How does JavaScript evaluate truthy and falsy values in an if condition?
In JavaScript, an if condition doesn't require a strict boolean; instead, any value is implicitly converted to true or false. Falsy values include false, 0, -0, 0n, "" (empty string), null, undefined, and NaN. All other values, including non-empty strings, non-zero numbers, objects, and arrays (even empty ones), are considered truthy and will cause the if block to execute.
What are some ways to refactor deeply nested if-else statements to make code more readable?
Deeply nested if-else statements can be refactored using early returns (also called guard clauses) to handle edge cases first and exit the function early, combining multiple conditions using logical operators (&& or ||) into a single if statement, replacing a chain of equality checks against one variable with a switch statement, or extracting complex nested logic into separate, well-named helper functions to improve readability and maintainability.
Explain short-circuit evaluation in the context of conditional statements in JavaScript.
Short-circuit evaluation refers to how JavaScript's logical operators (&& and ||) stop evaluating expressions as soon as the overall result is determined. With &&, if the first operand is falsy, the second operand is never evaluated because the result must be falsy. With ||, if the first operand is truthy, the second is never evaluated. This behavior is often used inside if conditions to safely check multiple conditions or avoid errors, such as 'if (user && user.isActive)', which avoids accessing 'isActive' on an undefined user.
Write a JavaScript program that checks if a given number is positive, negative, or zero, and prints an appropriate message using an if-else if-else ladder.
function checkNumber(num) { if (num > 0) { console.log(`${num} is positive`); } else if (num < 0) { console.log(`${num} is negative`); } else { console.log(`${num} is zero`); } } checkNumber(15); checkNumber(-8); checkNumber(0);
Write a function 'checkEligibility' that takes an age and a citizenship status (boolean) as parameters. Using nested if-else statements, print 'Eligible to vote' only if age is 18 or above AND the person is a citizen; otherwise, print an appropriate message explaining why they are not eligible.
function checkEligibility(age, isCitizen) { if (age >= 18) { if (isCitizen) { console.log("Eligible to vote"); } else { console.log("Not eligible: must be a citizen"); } } else { console.log("Not eligible: must be at least 18 years old"); } } checkEligibility(20, true); checkEligibility(20, false); checkEligibility(16, true);
Write a function 'classifyTriangle' that takes three side lengths as parameters and determines whether the triangle is equilateral, isosceles, or scalene using if-else statements, while also validating that the sides can actually form a valid triangle.
function classifyTriangle(a, b, c) { if (a + b <= c || b + c <= a || a + c <= b) { console.log("Invalid triangle: sides do not satisfy triangle inequality"); } else if (a === b && b === c) { console.log("Equilateral triangle"); } else if (a === b || b === c || a === c) { console.log("Isosceles triangle"); } else { console.log("Scalene triangle"); } } classifyTriangle(5, 5, 5); classifyTriangle(5, 5, 8); classifyTriangle(3, 4, 5); classifyTriangle(1, 2, 10);

The if-else statement is a core conditional control structure in JavaScript that allows programs to execute different code blocks based on whether a condition is true or false. It comes in several forms, including simple if statements, if-else if-else ladders for multiple conditions, nested if-else statements for hierarchical logic, and the ternary operator for concise single-line conditions. Writing clean conditional logic involves using strict equality, avoiding deep nesting, ordering conditions correctly, and always using curly braces for clarity and maintainability.

© 2026 CompileX. Maintained by Aditya Kumar Sharma.