Conditional Statements (if, else if, switch & Guard Clauses)
Welcome to Phase 4: Conditions! Conditional statements allow your JavaScript applications to make intelligent decisions based on changing data. In this masterclass guide, you will master single if branches, else if decision ladders, nested conditions, multi-condition logic with && and ||, ternary expressions, clean switch-case statements, modern Guard Clauses, and solve 6 real-world practice programs.
JavaScript lo code execution branching cheyyadaniki if, else if, mariyu else blocks vadathamu:
Given condition true aythe mathrame block lopali code execute avthundhi.
Multiple conditions ni sequential ga step-by-step check cheyyadaniki vadathamu.
Painunna conditions anni false ayinappudu default ga execute avthundhi.
"use strict";
const marks = 78;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 60) {
console.log("Grade B");
} else if (marks >= 40) {
console.log("Grade C");
} else {
console.log("Fail");
}
Oka if block lopala maroka if block rayadanni Nested Condition antaru. Rendunte ekkuva conditions ni combine cheyyadaniki logical && (AND), || (OR), and ! (NOT) vadathamu:
"use strict";
let age = 22;
let hasVoterId = true;
let isCitizen = true;
// Multiple conditions combined with &&
if (age >= 18 && hasVoterId && isCitizen) {
console.log("โ
Eligible to Vote in Elections!");
} else {
// Nested inspection
if (age < 18) {
console.log("โ Underage: You must be at least 18 years old.");
} else {
console.log("โ Missing Voter ID or Citizenship documents.");
}
}
Deep ga nested if-else blocks rayadam valla code readability padipothundi (called Pyramid of Doom). Guard Clauses tho invalid cases ni mundhugane check chesi early ga return chesi code ni clean ga unchavachu:
"use strict";
function processPayment(user, amount) {
// Guard Clause 1: Invalid user check
if (!user) {
return "Error: User profile not found!";
}
// Guard Clause 2: Negative amount check
if (amount <= 0) {
return "Error: Payment amount must be greater than zero!";
}
// Guard Clause 3: Insufficient balance check
if (user.balance < amount) {
return "Error: Insufficient funds in account!";
}
// Happy Path โ Clean and Flat!
user.balance -= amount;
return "Success: Transferred Rs." + amount + " | New Balance: Rs." + user.balance;
}
const account = { name: "Ravi", balance: 5000 };
console.log(processPayment(account, 1200));
Oka variable value ni multiple fixed constants tho compare cheyyadaniki switch statement best choice. break statement lekunte execution kindha unna cases loki fall-through avthundhi:
"use strict";
let dayNumber = 3;
let dayName;
switch (dayNumber) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
case 7:
dayName = "Weekend (Saturday/Sunday) ๐";
break;
default:
dayName = "Invalid Day Number (1-7 allowed)";
}
console.log("Day " + dayNumber + " is: " + dayName);
Condition lo pure boolean kakunda string or object pettinappudu JS implicit truthiness evaluate chesthundi. Eppudu strict === vadatam dwara accidental string-to-number coercions ni prevent cheyyavachu:
let username = "Ravi";
if (username) {
console.log("Hello, " + username); // Executes because non-empty string is Truthy!
}
Mastering conditions through 6 practical algorithms:
Program 1: Even or Odd Checker
"use strict";
let num = 47;
if (num % 2 === 0) {
console.log(num + " is EVEN");
} else {
console.log(num + " is ODD");
}
Program 2: Largest of Three Numbers
"use strict";
let a = 85, b = 92, c = 74;
if (a >= b && a >= c) {
console.log("Largest Number is: " + a);
} else if (b >= a && b >= c) {
console.log("Largest Number is: " + b);
} else {
console.log("Largest Number is: " + c);
}
Program 3: Voting Eligibility Checker
"use strict";
let voterAge = 19;
let message = voterAge >= 18
? "โ
Eligible to Vote!"
: "โ Not Eligible (Wait " + (18 - voterAge) + " more years)";
console.log(message);
Program 4: Full Grade Calculator
"use strict";
function calculateGrade(score) {
if (score < 0 || score > 100) return "Invalid Score!";
if (score >= 90) return "A+ (Outstanding)";
if (score >= 80) return "A (Excellent)";
if (score >= 70) return "B (Good)";
if (score >= 60) return "C (Average)";
if (score >= 40) return "D (Pass)";
return "F (Fail)";
}
console.log("Score 95:", calculateGrade(95));
console.log("Score 78:", calculateGrade(78));
console.log("Score 35:", calculateGrade(35));
Program 5: Leap Year Checker
"use strict";
function isLeapYear(year) {
// Leap year rule: divisible by 4 AND not 100, OR divisible by 400
if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)) {
return year + " is a LEAP YEAR ๐๏ธ";
}
return year + " is NOT a leap year";
}
console.log(isLeapYear(2024)); // Leap year
console.log(isLeapYear(2026)); // Not leap year
console.log(isLeapYear(2000)); // Leap year (divisible by 400)
console.log(isLeapYear(1900)); // Not leap year (century not divisible by 400)
Program 6: Simple Calculator using switch
"use strict";
function calculate(n1, operator, n2) {
let result;
switch (operator) {
case '+':
result = n1 + n2;
break;
case '-':
result = n1 - n2;
break;
case '*':
result = n1 * n2;
break;
case '/':
result = n2 !== 0 ? n1 / n2 : "Error: Cannot divide by zero!";
break;
case '%':
result = n1 % n2;
break;
default:
result = "Error: Unknown operator!";
}
return n1 + " " + operator + " " + n2 + " = " + result;
}
console.log(calculate(10, '+', 5));
console.log(calculate(20, '*', 3));
console.log(calculate(15, '/', 4));
console.log(calculate(10, '/', 0));
Run and inspect the combined grade evaluation program in our live compiler:
"use strict";
const studentName = "Ravi";
const marks = 78;
let grade;
if (marks >= 90) {
grade = "Grade A";
} else if (marks >= 60) {
grade = "Grade B";
} else if (marks >= 40) {
grade = "Grade C";
} else {
grade = "Fail";
}
console.log("Student:", studentName);
console.log("Marks:", marks);
console.log("Result:", grade);