The JavaScript if else Statement is a conditional statement used to execute different blocks of code depending on whether a specified condition is true or false. It allows a program to make decisions and control the flow of execution.
The if...else statement checks a condition. If the condition evaluates to true, JavaScript executes the if block. Otherwise, it executes the else block.
You can use the JavaScript if...else statement to validate user input, check numbers, compare values, calculate discounts, and perform different operations based on specific conditions.
JavaScript if…else Statement Syntax
The basic syntax of the JavaScript if...else statement is:
if (condition) {
// Code executes if the condition is true
} else {
// Code executes if the condition is false
}
The statement contains two main blocks:
- if: Executes when the specified condition evaluates to
true. - else: Executes when the condition evaluates to
false.
The else block is optional, but it is useful when you want to handle both possible outcomes of a condition.
JavaScript if…else Statement Example
The following example checks 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 not greater than 10");
}
Output:
The number is greater than 10
In this example, the variable number contains the value 15. JavaScript evaluates the condition number > 10.
Since the condition is true, the code inside the if block executes. The else block is skipped.
JavaScript if…else Statement With Numbers
You can use an if...else statement to check whether a number is even or odd.
let number = 7;
if (number % 2 === 0) {
console.log("The number is even");
} else {
console.log("The number is odd");
}
Output:
The number is odd
The modulo operator (%) returns the remainder after division. If a number is divisible by 2, its remainder is 0 and the number is even. Otherwise, it is odd.
JavaScript if…else Statement With Strings
The if...else statement can also compare string values.
let language = "JavaScript";
if (language === "JavaScript") {
console.log("Welcome to JavaScript");
} else {
console.log("Unknown programming language");
}
Output:
Welcome to JavaScript
In this example, JavaScript compares the value of language with the string "JavaScript" using the strict equality operator (===).
Because both values match, the if block executes.
JavaScript if…else Statement With Comparison Operators
Comparison operators are commonly used to evaluate conditions in JavaScript.
let age = 20;
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
Here, the >= operator checks whether the age is greater than or equal to 18. Since the condition is true, JavaScript displays the eligibility message.
Other comparison operators include:
| Operator | Description |
|---|---|
== |
Equal to |
=== |
Strictly equal to |
!= |
Not equal to |
!== |
Strictly not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
JavaScript if…else Statement With Logical Operators
You can combine multiple conditions using logical operators such as &&, ||, and !.
Using the AND (&&) Operator
The AND operator returns true only when both conditions are true.
let age = 25;
let hasLicense = true;
if (age >= 18 && hasLicense === true) {
console.log("You can drive");
} else {
console.log("You cannot drive");
}
Output:
You can drive
Both conditions are true, so JavaScript executes the if block.
Using the OR (||) Operator
The OR operator returns true when at least one condition is true.
let day = "Friday";
if (day === "Friday" || day === "Saturday") {
console.log("It is a weekend");
} else {
console.log("It is a working day");
}
Output:
It is a weekend
The condition is true because day matches "Friday".
Using the NOT (!) Operator
The NOT operator reverses a Boolean value. It changes true to false and false to true.
let isLoggedIn = false;
if (!isLoggedIn) {
console.log("Please log in");
} else {
console.log("Welcome back");
}
Output:
Please log in
Since isLoggedIn is false, the NOT operator changes the condition to true.
JavaScript if…else Statement Without Curly Braces
JavaScript allows you to omit curly braces when an if or else block contains only one statement.
let number = 10;
if (number > 5)
console.log("Number is greater than 5");
else
console.log("Number is not greater than 5");
Output:
Number is greater than 5
Although this syntax is valid, using curly braces is generally recommended because it makes code easier to read and helps prevent errors when additional statements are added.
JavaScript Nested if…else Statement
A nested if...else statement is an if...else statement placed inside another if or else block. It is useful when one decision depends on another condition.
let age = 22;
let hasID = true;
if (age >= 18) {
if (hasID) {
console.log("Access granted");
} else {
console.log("Please show your ID");
}
} else {
console.log("Access denied");
}
Output:
Access granted
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 an ID.
The nested condition determines whether access is granted.
JavaScript if…else Statement With User Input
You can use the if...else statement to process user input and display different results.
The following example uses the prompt() function to ask the user for their age.
let age = Number(prompt("Enter your age:"));
if (age >= 18) {
console.log("You are an adult");
} else {
console.log("You are a minor");
}
Example Input:
Enter your age: 21
Output:
You are an adult
The prompt() function receives input as a string. The Number() function converts that input into a number so that JavaScript can perform a numerical comparison.
JavaScript if…else Statement for Discount Calculation
You can use an if...else statement to calculate a discount based on a purchase amount.
let purchaseAmount = 3000;
let discount = 0;
if (purchaseAmount >= 5000) {
discount = 10;
} else {
discount = 5;
}
let discountAmount = purchaseAmount * discount / 100;
let totalAmount = purchaseAmount - discountAmount;
console.log("Discount: " + discount + "%");
console.log("Discount Amount: " + discountAmount);
console.log("Total Amount: " + totalAmount);
Output:
Discount: 5%
Discount Amount: 150
Total Amount: 2850
In this example, the purchase amount is 3000, which is less than 5000. Therefore, the else block assigns a 5% discount.
JavaScript if…else Statement With Boolean Values
You can directly use Boolean variables as conditions in an if...else statement.
let isAvailable = true;
if (isAvailable) {
console.log("The product is available");
} else {
console.log("The product is out of stock");
}
Output:
The product is available
Since isAvailable is true, JavaScript executes the first block.
JavaScript if…else Statement vs if Statement
Both statements are used for conditional execution, but they have a small difference.
| Feature | if Statement | if…else Statement |
|---|---|---|
| Conditions | Checks a condition | Checks a condition |
| True result | Executes the if block |
Executes the if block |
| False result | Skips the block | Executes the else block |
| Alternative block | Not included | Included |
| Use case | When only one condition needs handling | When both true and false outcomes need handling |
Example using an if statement:
let temperature = 35;
if (temperature > 30) {
console.log("The weather is hot");
}
Output:
The weather is hot
Use an if statement when you only need to execute code for a true condition. Use an if...else statement when you need to execute different code for both true and false conditions.