The if...else statement in JavaScript is used to execute different blocks of code depending on whether a specified condition is true or false. If the condition evaluates to true, the code inside the if block executes; otherwise, the code inside the else block executes. This statement is useful for making decisions in programs, such as checking whether a number is even or odd, determining whether a student has passed an exam, or verifying whether a person is eligible to vote. In this article, we will learn how the JavaScript if...else statement works, its syntax, examples, and common beginner mistakes.
Table of Contents
What Is the if...else Statement in JavaScript?
The if...else statement is a conditional statement that allows a program to choose between two execution paths.
- The if block executes when the condition is true.
- The else block executes when the condition is false.
Example:
// JavaScript program to demonstrate the if...else statement
let age = 16;
if (age >= 18) {
console.log("You are eligible to vote.");
} else {
console.log("You are not eligible to vote.");
}
Output:
You are not eligible to vote.
In this example, the condition age >= 18 evaluates to false because the age is 16. Therefore, JavaScript executes the else block.
Syntax of the if...else Statement
The if...else statement contains a condition followed by two code blocks.
Syntax:
if (condition) {
// Code executed when the condition is true
} else {
// Code executed when the condition is false
}
The condition is evaluated first. JavaScript executes the if block if the condition is truthy; otherwise, it executes the else block.
How Does the if...else Statement Work?
The if...else statement follows a simple decision-making process.
-
JavaScript evaluates the specified condition.
-
If the condition is true, the statements inside the if block execute.
-
If the condition is false, the statements inside the else block execute.
-
After executing the selected block, the program continues with the next statement.
Example:
// JavaScript program to demonstrate how if...else works
let number = 10;
if (number > 0) {
console.log("The number is positive.");
} else {
console.log("The number is not positive.");
}
console.log("Program completed.");
Output:
The number is positive.
Program completed.
Here, the condition number > 0 is true, so the first message is displayed. The else block is skipped, and the program continues to the next statement.
Simple if...else Statement Example
The if...else statement can be used to check a condition and execute the appropriate block of code.
Example:
// JavaScript program to check whether a student has passed
let marks = 28;
if (marks >= 35) {
console.log("The student has passed.");
} else {
console.log("The student has failed.");
}
Output:
The student has failed.
In this example, the program checks whether the marks are at least 35. Since the student has scored 28, the condition is false, and the else block executes.
if...else with Comparison Operators
Comparison operators are commonly used with if...else statements to compare values.
Common comparison operators include:
-
> checks whether one value is greater than another.
-
< checks whether one value is less than another.
-
>= checks whether one value is greater than or equal to another.
-
<= checks whether one value is less than or equal to another.
-
=== checks strict equality.
-
!== checks strict inequality.
Example:
// JavaScript program to compare two numbers using if...else
let a = 15;
let b = 20;
if (a > b) {
console.log("a is greater than b.");
} else {
console.log("a is not greater than b.");
}
Output:
a is not greater than b.
Here, 15 is not greater than 20, so the condition is false and the else block executes.
if...else with Logical Operators
Logical operators allow multiple conditions to be combined in an if...else statement.
The main logical operators are:
-
&& (AND) evaluates to a truthy result when both operands are truthy.
-
|| (OR) evaluates to a truthy result when at least one operand is truthy.
-
! (NOT) reverses the truthiness of a value.
Example:
// JavaScript program to demonstrate logical operators with if...else
let age = 22;
let hasID = true;
if (age >= 18 && hasID) {
console.log("Entry is allowed.");
} else {
console.log("Entry is not allowed.");
}
Output:
Entry is allowed.
In this example, both conditions are satisfied: the age is at least 18, and hasID is true. Therefore, the if block executes.
Nested if...else Statement
A nested if...else statement is an if...else statement placed inside another conditional block. It is useful when a program needs to check multiple related conditions.
Example:
// JavaScript program to demonstrate a nested if...else statement
let age = 20;
let hasLicense = true;
if (age >= 18) {
if (hasLicense) {
console.log("You can drive.");
} else {
console.log("You need a driving license.");
}
} else {
console.log("You are too young to drive.");
}
Output:
You can drive.
In this example, JavaScript first checks whether the person is at least 18 years old. If the condition is true, it checks whether the person has a driving license. Since both conditions are satisfied, the program displays the first message.
Difference Between if and if...else
The if and if...else statements are both used for decision-making, but they handle false conditions differently.
| Basis | if Statement | if...else Statement |
|---|---|---|
| Purpose | Executes code when a condition is true | Chooses between two blocks |
| When the condition is true | Executes the if block | Executes the if block |
| When the condition is false | Skips the if block | Executes the else block |
| Number of alternatives | One conditional block | Two alternative blocks |
| Common use | Performing an optional action | Choosing between two outcomes |
Example using if:
// JavaScript program to demonstrate the if statement
let temperature = 35;
if (temperature > 30) {
console.log("The weather is hot.");
}
Output:
The weather is hot.
Example using if...else:
// JavaScript program to demonstrate the if...else statement
let temperature = 25;
if (temperature > 30) {
console.log("The weather is hot.");
} else {
console.log("The weather is not hot.");
}
Output:
The weather is not hot.
The if statement does not provide an alternative block, while if...else handles both true and false conditions.
Advantages of the if...else Statement
The if...else statement offers several benefits in JavaScript programming.
- Decision-making: It allows programs to choose between two possible outcomes.
- Simple syntax: It is easy for beginners to understand and use.
- Condition checking: It works with comparison and logical operators to evaluate different situations.
- Better control flow: It helps programs respond differently based on user input or variable values.
- Flexible logic: It can be combined with nested conditions and other conditional statements to solve more complex problems.
Common Beginner Mistakes
- Using the assignment operator instead of a comparison operator: Using = assigns a value, while === compares values and types. Use the appropriate operator when checking conditions.
- Forgetting curly braces: Curly braces help group statements into the correct block and prevent mistakes when adding more statements.
- Writing incorrect conditions: Check comparison and logical operators carefully to ensure the condition matches the intended behavior.
- Confusing if...else with else if: The else block handles the false outcome of an if condition, while else if allows additional conditions to be checked.
- Creating unnecessary nested conditions: Too many nested if...else statements can make code difficult to read. Use simpler conditions or else if when appropriate.
Conclusion
The if...else statement is an essential decision-making feature in JavaScript. It allows a program to execute one block of code when a condition is true and another block when the condition is false. By combining if...else with comparison operators, logical operators, and nested conditions, developers can build programs that respond to different situations. Understanding this statement provides a strong foundation for learning more advanced conditional logic in JavaScript.
FAQs
1. What is the if...else statement in JavaScript?
The if...else statement executes one block of code when a condition is true and another block when the condition is false.
2. What happens when the if condition is false?
JavaScript skips the if block and executes the statements inside the else block.
3. Can we use logical operators with if...else?
Yes. Logical operators such as &&, ||, and ! can be used to combine or modify conditions.
4. What is a nested if...else statement?
A nested if...else statement is a conditional statement placed inside another conditional block to check additional conditions.
5. What is the difference between if and if...else?
An if statement executes code only when its condition is true, while an if...else statement provides separate blocks for true and false conditions.
0 Comments