A JavaScript program often needs to choose what should happen next. For example, an application may need to check whether a student has passed an examination, whether a customer is eligible for a discount, or whether a user has entered the correct password. These decisions are handled using conditional statements.
A condition is an expression whose result can be evaluated as true or false. JavaScript uses that result to decide whether a particular block of code should execute.
Conditional statements are therefore an important part of program control. They allow the same program to produce different results when the input or situation changes.
A condition is a logical expression that JavaScript evaluates while executing a program. The expression normally produces a Boolean result: true or false.
For example:
let age = 21; age >= 18
The expression above becomes true because 21 is greater than or equal to 18.
Another example is:
let marks = 32; marks >= 40
This expression becomes false because 32 is less than 40.
Without conditional statements, JavaScript would execute instructions in a fixed sequence. Conditions give a program the ability to respond according to the data it receives.
For example, a result-processing program can display different messages depending on marks:
let marks = 68;
if(marks >= 40)
{
console.log("Pass");
}
If the value of marks changes to 25, the same condition becomes false. This ability to make decisions is what makes programs dynamic and useful.
JavaScript provides several ways to implement decision-making logic.
| Statement | Purpose |
|---|---|
| if | Executes code when a condition is true. |
| if...else | Chooses between two possible outcomes. |
| else if | Checks multiple conditions in sequence. |
| Nested if | Places one condition inside another condition. |
| switch | Compares one expression with multiple fixed values. |
The if statement is the simplest way to make a decision. JavaScript executes the statements inside the block only when the specified condition evaluates to true.
if(condition)
{
// statements to execute
}
let age = 19;
if(age >= 18)
{
console.log("Age requirement satisfied");
}
Age requirement satisfied
Because the value of age is 19, the expression age >= 18 evaluates to true.
let number = 24;
if(number % 2 === 0)
{
console.log("The number is even");
}
The number is even
The modulus operator % gives the remainder after division. An even number produces a remainder of zero when divided by 2.
The if...else statement is useful when a program has two possible outcomes. One block executes when the condition is true, while another block executes when it is false.
if(condition)
{
// Executes when condition is true
}
else
{
// Executes when condition is false
}
let marks = 36;
if(marks >= 40)
{
console.log("Student has passed");
}
else
{
console.log("Student has failed");
}
Student has failed
Here, 36 is less than 40, so JavaScript executes the else block.
let isLoggedIn = false;
if(isLoggedIn)
{
console.log("Welcome to your account");
}
else
{
console.log("Please log in first");
}
Please log in first
This type of condition is common in websites where different content is shown depending on whether a user is logged in.
When a program has more than two possible outcomes, multiple conditions can be checked using an else if ladder.
JavaScript evaluates the conditions from top to bottom. When it finds the first true condition, its associated block is executed and the remaining conditions are skipped.
if(condition1)
{
// Block 1
}
else if(condition2)
{
// Block 2
}
else if(condition3)
{
// Block 3
}
else
{
// Default block
}
let marks = 76;
if(marks >= 90)
{
console.log("Grade A+");
}
else if(marks >= 75)
{
console.log("Grade A");
}
else if(marks >= 60)
{
console.log("Grade B");
}
else if(marks >= 40)
{
console.log("Grade C");
}
else
{
console.log("Fail");
}
Grade A
The value 76 does not satisfy the first condition, but it satisfies marks >= 75. Therefore, JavaScript executes that block and stops checking the remaining conditions.
The order of conditions matters in an else if ladder. JavaScript stops at the first condition that evaluates to true.
For example, this order is appropriate:
if(marks >= 90)
{
console.log("A+");
}
else if(marks >= 75)
{
console.log("A");
}
else if(marks >= 60)
{
console.log("B");
}
If a broader condition is placed first, later conditions may never get a chance to execute. Therefore, conditions should normally be arranged from the most restrictive or highest range to the lowest range when checking numerical ranges.
A nested if is an if statement placed inside another if statement. It can be useful when the second decision should only be considered after the first condition has been satisfied.
if(condition1)
{
if(condition2)
{
// statements
}
}
let age = 20;
let marks = 72;
if(age >= 18)
{
if(marks >= 60)
{
console.log("Eligible for the course");
}
}
Eligible for the course
The inner condition is checked only after the age requirement has been satisfied.
A nested condition can also contain an else block to provide feedback when an inner condition fails.
let age = 22;
let documentsSubmitted = false;
if(age >= 18)
{
if(documentsSubmitted)
{
console.log("Application accepted");
}
else
{
console.log("Submit the required documents");
}
}
else
{
console.log("Age requirement not satisfied");
}
Submit the required documents
Comparison operators are frequently used to create conditions. They compare values and produce a Boolean result.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Loose equality | 5 == "5" | true |
| === | Strict equality | 5 === "5" | false |
| != | Loose inequality | 5 != 3 | true |
| !== | Strict inequality | 5 !== "5" | true |
| > | Greater than | 10 > 5 | true |
| < | Less than | 4 < 8 | true |
| >= | Greater than or equal to | 18 >= 18 | true |
| <= | Less than or equal to | 10 <= 12 | true |
The === operator performs a strict comparison. It checks both the value and the data type.
console.log(10 == "10"); console.log(10 === "10");
true false
The first comparison allows type conversion, while the strict comparison requires both operands to have the same type as well as the same value. For predictable program logic, === is generally preferred when strict equality is intended.
Logical operators allow multiple conditions to be combined.
| Operator | Name | Meaning |
|---|---|---|
| && | AND | True when both conditions are true. |
| || | OR | True when at least one condition is true. |
| ! | NOT | Reverses a Boolean value. |
The AND operator is useful when all required conditions must be satisfied.
let age = 21;
let hasId = true;
if(age >= 18 && hasId)
{
console.log("Entry allowed");
}
else
{
console.log("Entry denied");
}
Entry allowed
The OR operator is useful when at least one of several conditions can satisfy the requirement.
let hasEmail = false;
let hasMobile = true;
if(hasEmail || hasMobile)
{
console.log("Contact information available");
}
else
{
console.log("Contact information required");
}
Contact information available
let paymentCompleted = false;
if(!paymentCompleted)
{
console.log("Payment is still pending");
}
Payment is still pending
The NOT operator reverses the Boolean value. Since paymentCompleted is false, !paymentCompleted becomes true.
JavaScript does not require every condition to contain an explicit comparison. Values can also be evaluated directly in a conditional statement.
Some values are treated as falsy, while most other values are treated as truthy.
let username = "";
if(username)
{
console.log("Username available");
}
else
{
console.log("Username is empty");
}
Username is empty
An empty string is falsy, so JavaScript executes the else block.
The switch statement is useful when one expression needs to be compared against several fixed values. It can make such logic easier to read than a long series of equality checks.
switch(expression)
{
case value1:
// statements
break;
case value2:
// statements
break;
default:
// default statements
}
let department = "CS";
switch(department)
{
case "CS":
console.log("Computer Science");
break;
case "IT":
console.log("Information Technology");
break;
case "EC":
console.log("Electronics");
break;
default:
console.log("Department not found");
}
Computer Science
The break statement ends the current switch execution. Without it, JavaScript may continue into the following cases. This behavior is called fall-through.
let option = 1;
switch(option)
{
case 1:
console.log("First option");
break;
case 2:
console.log("Second option");
break;
default:
console.log("Invalid option");
}
First option
The break statement prevents the second case from being executed after the first case.
The default block provides a fallback when none of the case values match.
let paymentMode = "Cheque";
switch(paymentMode)
{
case "UPI":
console.log("UPI payment selected");
break;
case "Card":
console.log("Card payment selected");
break;
case "Cash":
console.log("Cash payment selected");
break;
default:
console.log("Unsupported payment mode");
}
Unsupported payment mode
| if...else | switch |
|---|---|
| Suitable for conditions and ranges. | Suitable for comparing one expression with fixed values. |
| Can use comparison and logical operators. | Usually used for exact case matching. |
| Useful for complex decision logic. | Useful for menu-like or fixed choices. |
| Can handle conditions such as marks >= 60. | Works naturally with values such as "CS", "IT", or 1, 2, 3. |
Conditions are frequently used in e-commerce applications. The following example calculates a discount according to the purchase amount.
let amount = 6500;
let discount;
if(amount >= 10000)
{
discount = 20;
}
else if(amount >= 5000)
{
discount = 10;
}
else if(amount >= 2000)
{
discount = 5;
}
else
{
discount = 0;
}
console.log("Discount: " + discount + "%");
Discount: 10%
Because the purchase amount is 6500, the program selects the 10 percent discount category.
let temperature = 38;
if(temperature >= 40)
{
console.log("Very hot");
}
else if(temperature >= 30)
{
console.log("Hot");
}
else if(temperature >= 20)
{
console.log("Comfortable");
}
else
{
console.log("Cool");
}
Hot
Beginners often encounter errors because conditional expressions are small but sensitive to operators, data types, and logical structure.
| Mistake | Better Approach |
|---|---|
| Using = when a comparison is required. | Use === for strict equality. |
| Putting a broad condition before a more specific condition. | Arrange range-based conditions carefully. |
| Forgetting break in switch cases. | Add break when fall-through is not intended. |
| Creating too many nested if statements. | Consider simplifying the logic or combining conditions. |
| Ignoring false or unexpected input values. | Test different possible inputs. |
| Using loose comparison without understanding type conversion. | Prefer strict comparison when appropriate. |
Conditional logic appears in many types of web applications. Some common examples include:
A conditional statement controls which block of code should execute based on whether a condition is true or false. Common conditional statements include if, if...else, else if, and switch.
The if statement executes a block of code only when its condition evaluates to true.
let age = 20;
if(age >= 18)
{
console.log("Adult");
}
Here, the message is printed because the condition is true.
An if statement provides an action only for the true case. An if...else statement provides two possible paths: one for true and another for false.
if(marks >= 40)
{
console.log("Pass");
}
else
{
console.log("Fail");
}
An else if ladder is used when several conditions need to be checked. JavaScript evaluates the conditions from top to bottom and executes the first matching block.
A nested if is an if statement inside another if statement. It is useful when one decision depends on another decision.
The == operator performs loose equality and may convert data types before comparison. The === operator performs strict equality and checks both value and type.
console.log(5 == "5"); console.log(5 === "5");
Output:
true false
The main logical operators are &&, ||, and !.
The switch statement compares one expression against multiple case values. It is particularly useful when the possible choices are fixed values.
The break statement stops execution of the switch after a matching case. Without break, execution can continue into subsequent cases.
If none of the case values matches the switch expression, JavaScript executes the default block when one is provided.
When a value is used directly as a condition, JavaScript converts it to a Boolean context. Values such as false, 0, empty string, null, undefined, and NaN are commonly treated as falsy. Most other values are truthy.
Yes. Logical operators can combine multiple conditions.
let age = 25;
let hasTicket = true;
if(age >= 18 && hasTicket)
{
console.log("Entry allowed");
}
Use switch when one expression needs to be compared with several fixed values. For ranges, complex expressions, or conditions involving different variables, an if...else structure is generally more suitable.
JavaScript stops checking an else if ladder after finding the first true condition. Therefore, placing a broad condition too early can prevent later conditions from being reached.
Use meaningful variable names, keep expressions simple, avoid unnecessary nesting, prefer strict comparisons where appropriate, and test different input scenarios.
| Concept | Key Point |
|---|---|
| if | Runs code when a condition is true. |
| if...else | Provides two possible execution paths. |
| else if | Checks multiple conditions sequentially. |
| Nested if | Places one condition inside another. |
| && | Both conditions must be true. |
| || | At least one condition must be true. |
| ! | Reverses a Boolean value. |
| switch | Compares one expression with fixed case values. |
| break | Stops switch execution. |
| default | Runs when no switch case matches. |
JavaScript conditions allow programs to make decisions according to changing data and user actions. The if statement is useful for a single decision, while if...else provides two alternatives. An else if ladder can handle multiple conditions, and a nested if can represent dependent decisions.
Logical operators such as &&, ||, and ! help combine conditions. The switch statement provides a convenient way to compare one expression with several fixed values.
A good understanding of conditional statements is essential before moving to topics such as JavaScript loops, functions, arrays, DOM manipulation, events, and asynchronous programming.