JavaScript If-Else Statement (Complete Guide with Examples)
The JavaScript if-else statement is a fundamental control structure that allows a program to make decisions based on specific conditions. It enables JavaScript to execute different blocks of code depending on whether a condition evaluates to true or false.
Conditional statements are widely used in real-world applications such as form validation, authentication systems, dynamic user interfaces, and decision-based logic.
JavaScript provides the following three types of conditional statements:
- If statement
- If...else statement
- If...else if statement
JavaScript If Statement
The if statement is used to execute a block of code only when a specified
condition is true. If the condition is false, the code inside the
if block is skipped.
if (condition) {
// code to execute if the condition is true
}
Example: Check User Eligibility
JavaScript Example
// Check voting eligibility
let age = 21;
if (age >= 18) {
console.log("You are eligible to vote.");
}
Try it Yourself ยป
JavaScript If...Else Statement
The if...else statement executes one block of code when the condition is true and a different block when the condition is false. This structure is ideal when you need exactly two possible outcomes.
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
Example: Check Login Status
JavaScript Example
// Check user login status
let isLoggedIn = true;
if (isLoggedIn) {
console.log("Welcome back! You are logged in.");
} else {
console.log("Please log in to continue.");
}
Try it Yourself ยป
JavaScript If...Else If Statement
The if...else if statement is used to test multiple conditions sequentially.
JavaScript executes the first block of code whose condition evaluates to
true. If none of the conditions are true, the else block is executed.
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else {
// code if all conditions are false
}
Example: Grade Evaluation System
JavaScript Example
// Grade evaluation system
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: Fail");
}
Try it Yourself ยป