The JavaScript if...else statement is a conditional statement that allows a program to execute different blocks of code depending on whether a condition is true or false. It is commonly used for decision-making tasks, such as checking whether a student has passed an examination, determining voting eligibility, or verifying a user's login status. In this article, you will learn the syntax, working, examples, advantages, and common mistakes associated with the JavaScript if...else statement.
Table of Contents
What Is the JavaScript if...else Statement?
The JavaScript if...else statement executes one block of code when a condition evaluates to a truthy value and another block when the condition evaluates to a falsy value.
It provides two alternative paths for program execution. If the condition is true, the if block runs. Otherwise, the else block runs.
For example, a program can use an if...else statement to check whether a student's marks meet the passing requirement. If the marks are sufficient, the program displays a passing message. Otherwise, it displays a message indicating that the student has failed.
Syntax of the if...else Statement
The basic syntax of the JavaScript if...else statement is shown below.
if (condition) {
// Code executed when the condition is true
} else {
// Code executed when the condition is false
}
The syntax contains the following parts.
- if: Specifies the condition to evaluate.
- condition: An expression evaluated according to JavaScript's truthiness rules.
- if block: Contains statements executed when the condition is truthy.
- else: Defines the alternative block.
- else block: Contains statements executed when the condition is falsy.
The else keyword does not require a separate condition because it runs whenever the if condition is falsy.
How Does the if...else Statement Work?
The if...else statement follows a straightforward decision-making process.
- JavaScript evaluates the condition inside the parentheses.
- If the condition is truthy, the statements inside the if block execute.
- If the condition is falsy, the statements inside the else block execute.
- After executing one block, the program continues with the statement following the conditional structure.
The following example demonstrates this process.
// Check whether a number is greater than 10.
let number = 15;
if (number > 10) {
console.log("The number is greater than 10.");
} else {
console.log("The number is 10 or less.");
}
Output:
The number is greater than 10.
In this example, the condition number > 10 evaluates to true because the value of number is 15. Therefore, the if block executes, and the else block is skipped.
If the value were 8, the condition would be false, and the program would display The number is 10 or less. instead.
Simple Example of the if...else Statement
The following example checks whether a person is an adult based on their age.
// Check whether a person is an adult.
let age = 16;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are not an adult.");
}
Output:
You are not an adult.
The condition age >= 18 evaluates to false because the age is 16. As a result, the else block executes.
If the age were 20, the program would display You are an adult.
Checking Whether a Number Is Positive or Not
The if...else statement can determine whether a number is positive by checking whether it is greater than zero.
// Check whether a number is positive.
let number = -5;
if (number > 0) {
console.log("The number is positive.");
} else {
console.log("The number is not positive.");
}
Output:
The number is not positive.
Since -5 is less than zero, the condition evaluates to false, and the else block executes.
This example treats zero as not positive. A separate condition would be needed to distinguish zero from negative numbers.
Checking Voting Eligibility
The if...else statement can check whether a person meets the minimum voting age of 18 years.
// Check voting eligibility based on age.
let age = 19;
if (age >= 18) {
console.log("You are eligible to vote.");
} else {
console.log("You are not eligible to vote.");
}
Output:
You are eligible to vote.
The condition is true because the age is 19. Therefore, the program displays the eligibility message.
If the age were 17, the else block would execute and display the alternative message.
Checking Pass or Fail
Another common use of the if...else statement is checking whether a student has passed an examination.
// Check whether a student has passed an examination.
let marks = 35;
if (marks >= 40) {
console.log("The student has passed.");
} else {
console.log("The student has failed.");
}
Output:
The student has failed.
The passing requirement in this example is 40 marks. Since the student scored 35, the condition evaluates to false, and the program displays the failure message.
If the marks were 60, the program would display The student has passed.
Using Comparison Operators in if...else
Comparison operators compare two values and return a Boolean result. They are frequently used in if...else conditions.
The following table lists common comparison operators.
| Operator | Description | Example |
|---|---|---|
| == | Checks equality after type conversion when necessary. | 5 == "5" |
| === | Checks strict equality without type conversion. | 5 === 5 |
| != | Checks inequality after type conversion when necessary. | 5 != 3 |
| !== | Checks strict inequality. | 5 !== "5" |
| > | Checks whether the left value is greater. | 10 > 5 |
| < | Checks whether the left value is smaller. | 3 < 8 |
| >= | Checks whether the left value is greater than or equal to the right value. | 10 >= 10 |
| <= | Checks whether the left value is smaller than or equal to the right value. | 4 <= 6 |
Example:
// Check whether a person has reached the required age.
let age = 17;
if (age >= 18) {
console.log("Age requirement satisfied.");
} else {
console.log("Age requirement not satisfied.");
}
Output:
Age requirement not satisfied.
The condition evaluates to false because 17 is less than 18. Therefore, the else block executes.
Strict equality (===) is generally preferred when comparing values because it avoids unexpected type conversions.
Using Logical Operators in if...else
Logical operators allow you to combine multiple conditions in an if...else statement.
The three main logical operators are:
-
AND (&&): The combined condition is truthy when both operands are truthy.
-
OR (||): The combined condition is truthy when at least one operand is truthy.
-
NOT (!): Reverses the truthiness of a value.
Example using the AND operator:
// Check whether a student meets both requirements.
let marks = 80;
let attendance = 90;
if (marks >= 40 && attendance >= 75) {
console.log("The student meets both requirements.");
} else {
console.log("The student does not meet both requirements.");
}
Output:
The student meets both requirements.
Both conditions are true because the marks are at least 40 and attendance is at least 75. Therefore, the if block executes.
Logical operators are helpful when a decision depends on several requirements.
Nested if...else Statements
A nested if...else statement is a conditional structure placed inside another conditional block. It allows a program to evaluate additional conditions after making an initial decision.
Example:
// Check whether a student qualifies for a scholarship.
let marks = 85;
let attendance = 90;
if (marks >= 75) {
if (attendance >= 80) {
console.log("The student qualifies for the scholarship.");
} else {
console.log("Attendance is too low.");
}
} else {
console.log("Marks are too low.");
}
Output:
The student qualifies for the scholarship.
The program first checks whether the marks are at least 75. Since this condition is true, it checks whether attendance is at least 80.
Both conditions are satisfied, so the scholarship message is displayed.
Nested conditions are useful for dependent decisions, but too many levels of nesting can make code difficult to read.
Difference Between if and if...else
Both statements evaluate conditions, but they differ in how they handle a false condition.
| Feature | if Statement | if...else Statement |
|---|---|---|
| Purpose | Executes code when a condition is truthy. | Chooses between two alternative blocks. |
| False condition | Skips the if block. | Executes the else block. |
| Number of branches | One conditional branch. | Two alternative branches. |
| Use case | Performing an action only when a condition is satisfied. | Handling both possible outcomes. |
Example using if:
// Display a message only when the condition is true.
let number = 5;
if (number > 0) {
console.log("The number is positive.");
}
Output:
The number is positive.
Example using if...else:
// Display a message for either outcome.
let number = -5;
if (number > 0) {
console.log("The number is positive.");
} else {
console.log("The number is not positive.");
}
Output:
The number is not positive.
The second example handles both outcomes, while the first performs an action only when its condition is truthy.
Advantages of the if...else Statement
The JavaScript if...else statement provides several advantages.
- Decision-making: It allows a program to choose between two outcomes.
- Simple syntax: Its structure is easy for beginners to understand.
- Conditional execution: It executes only the block appropriate to the evaluated condition.
- Flexible conditions: It supports comparison operators, logical operators, and truthy or falsy values.
- Practical applications: It can be used for validation, eligibility checks, login conditions, and other programming tasks.
These advantages make if...else an important part of JavaScript programming.
Common Mistakes to Avoid
-
Using assignment instead of comparison. Writing if (age = 18) assigns a value instead of checking whether the age equals 18. Use if (age === 18) for strict equality.
-
Forgetting curly braces. Missing braces can cause statements to execute outside the intended conditional block. Using braces consistently improves readability and prevents errors.
-
Placing the else block incorrectly. The else keyword must follow its corresponding if block. It cannot be used independently without a matching if.
-
Ignoring truthy and falsy values. JavaScript conditions do not require Boolean expressions. Values such as 0, "", null, undefined, and NaN are falsy, while non-empty strings and non-zero numbers are truthy.
-
Using unnecessary nested conditions. Too many nested if...else blocks can make a program difficult to maintain. Consider combining suitable conditions with logical operators when doing so keeps the code clear.
Frequently Asked Questions
1. What is the if...else statement in JavaScript?
The if...else statement executes one block when a condition is truthy and another block when the condition is falsy.
2. Is the else block compulsory in JavaScript?
No. The else block is optional. It is needed only when you want to handle the alternative outcome explicitly.
3. Can we use multiple conditions in an if...else statement?
Yes. You can combine multiple conditions using logical operators such as && and ||.
4. What is a nested if...else statement?
A nested if...else statement is a conditional structure placed inside another conditional block to evaluate additional conditions.
5. What is the difference between if and if...else?
An if statement executes code only when its condition is truthy, while an if...else statement provides separate blocks for truthy and falsy outcomes.
0 Comments