Conditional statements form the analytical backbone of computer algorithms, enabling software to inspect environmental variables and make dynamic decisions at runtime. JavaScript provides the if, else if, and else keywords to construct multi-branch decision trees.
The condition inside parentheses is evaluated for truthiness. If the condition is truthy, the corresponding block executes and remaining branches are skipped:
const examScore = 84;
if (examScore >= 90) {
console.log("Grade: A+ (Outstanding Academic Distinction)");
} else if (examScore >= 80) {
console.log("Grade: A (First Class Honors)");
} else if (examScore >= 60) {
console.log("Grade: B (Second Division)");
} else if (examScore >= 40) {
console.log("Grade: C (Pass Division)");
} else {
console.log("Grade: F (Failed - Remedial Exam Required)");
}
When multiple conditions must be checked sequentially, beginners often nest if statements inside each other, creating the dreaded "Pyramid of Doom". Modern software engineering replaces nested blocks with clean Guard Clauses:
// BAD PRACTICE: Deeply Nested "Pyramid of Doom"
function registerStudent(student) {
if (student) {
if (student.age >= 18) {
if (student.feesPaid) {
return "Enrollment Complete!";
} else {
return "Payment Pending.";
}
} else {
return "Must be at least 18 years old.";
}
} else {
return "Student data missing.";
}
}
// CLEAN CODE: Guard Clauses (Early Exit Pattern)
function registerStudentClean(student) {
if (!student) return "Student data missing.";
if (student.age < 18) return "Must be at least 18 years old.";
if (!student.feesPaid) return "Payment Pending.";
return "Enrollment Complete!";
}
Exam Question: "Write a JavaScript program using if..else to determine if a given year is a Leap Year."
function isLeapYear(year) {
// Leap year rule: Divisible by 4 AND (NOT divisible by 100 OR divisible by 400)
if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)) {
return `${year} is a Leap Year (366 Days)`;
} else {
return `${year} is a Common Year (365 Days)`;
}
}
console.log(isLeapYear(2024)); // Leap Year
console.log(isLeapYear(1900)); // Common Year (Divisible by 100 but not 400)
console.log(isLeapYear(2000)); // Leap Year
When you need to compare a single expression against dozens of potential matching values, what is cleaner than if..else? Proceed to: JavaScript Switch Case Statement →
Accelerate your JavaScript mastery by studying these tightly connected core tutorials:
Multi-way branching syntax and case fallthrough.
Writing robust conditional expressions.
Conditional repetitive execution.
Counter-controlled iteration loops.