Programs need to make decisions. Should we show this message or that one? Is the user old enough? Did they enter valid data? If/else statements let your code choose different paths based on conditions. They're the fundamental building blocks of program logic. Let's master conditional statements!
What Are Conditional Statements?
Conditional statements execute different code based on whether a condition is true or false. Think of them as decision points in your program.
Real-world analogy:
"IF it's raining, THEN take an umbrella, ELSE leave it at home."
"IF age is 18 or over, THEN allow entry, ELSE deny entry."
// Basic structure
if (condition) {
// Code runs if condition is true
}
// With else
if (condition) {
// Code runs if condition is true
} else {
// Code runs if condition is false
}The Basic If Statement
The simplest conditional: execute code only if a condition is true.
Syntax
if (condition) {
// Code to execute if condition is true
}Simple Examples
// Check if number is positive
let number = 10;
if (number > 0) {
console.log("Number is positive");
}
// Output: "Number is positive"
// Check if string is not empty
let username = "john";
if (username) { // Truthy check
console.log("Welcome, " + username);
}
// Output: "Welcome, john"
// Check if user is adult
let age = 20;
if (age >= 18) {
console.log("You can vote");
}
// Output: "You can vote"
// Multiple statements in block
let score = 95;
if (score >= 90) {
console.log("Excellent!");
console.log("You got an A");
console.log("Keep it up!");
}
// All three messages printWithout Curly Braces (Not Recommended)
// If body has only one statement, braces are optional
if (age >= 18)
console.log("Adult"); // This works
// But this can cause bugs:
if (age >= 18)
console.log("Adult");
console.log("Can vote"); // Always executes! Not part of if
// Always use braces for clarity:
if (age >= 18) {
console.log("Adult");
console.log("Can vote"); // ✅ Now both are conditional
}Best Practice: Always use curly braces {} even for single-line if statements. It prevents bugs and makes code more maintainable.
If/Else Statement
Execute one block of code if condition is true, another block if it's false.
Syntax
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}Examples
// Check if number is even or odd
let num = 7;
if (num % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}
// Output: "Odd"
// Age verification
let age = 15;
if (age >= 18) {
console.log("Access granted");
} else {
console.log("Access denied");
}
// Output: "Access denied"
// Temperature check
let temp = 30;
if (temp > 25) {
console.log("It's hot!");
} else {
console.log("It's cool!");
}
// Output: "It's hot!"
// Login check
let isLoggedIn = false;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in");
}
// Output: "Please log in"Practical Example: Form Validation
function validatePassword(password) {
if (password.length >= 8) {
console.log("Password is valid");
return true;
} else {
console.log("Password too short");
return false;
}
}
validatePassword("abc123"); // "Password too short"
validatePassword("abc12345"); // "Password is valid"
// Shorter version
function checkAge(age) {
if (age >= 18) {
return "Adult";
} else {
return "Minor";
}
}
console.log(checkAge(20)); // "Adult"
console.log(checkAge(15)); // "Minor"Else If Statement
Check multiple conditions in sequence. The first true condition executes, then the rest are skipped.
Syntax
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition1 is false and condition2 is true
} else if (condition3) {
// Code if condition1 and condition2 are false and condition3 is true
} else {
// Code if all conditions are false
}Grade Calculator
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B"); // This executes
} else if (score >= 70) {
console.log("Grade: C");
} else if (score >= 60) {
console.log("Grade: D");
} else {
console.log("Grade: F");
}
// Output: "Grade: B"
// Important: Only the first true condition executes
let num = 95;
if (num >= 50) {
console.log("Greater than 50"); // This executes
} else if (num >= 90) {
console.log("Greater than 90"); // Skipped even though true!
} else if (num >= 100) {
console.log("Greater than 100"); // Skipped
}
// Output: "Greater than 50"Multiple Conditions Example
function getTimeGreeting(hour) {
if (hour < 12) {
return "Good morning!";
} else if (hour < 18) {
return "Good afternoon!";
} else if (hour < 22) {
return "Good evening!";
} else {
return "Good night!";
}
}
console.log(getTimeGreeting(9)); // "Good morning!"
console.log(getTimeGreeting(14)); // "Good afternoon!"
console.log(getTimeGreeting(19)); // "Good evening!"
console.log(getTimeGreeting(23)); // "Good night!"
// Traffic light system
function getTrafficAction(light) {
if (light === "green") {
return "Go";
} else if (light === "yellow") {
return "Slow down";
} else if (light === "red") {
return "Stop";
} else {
return "Light malfunction";
}
}
console.log(getTrafficAction("green")); // "Go"
console.log(getTrafficAction("red")); // "Stop"
console.log(getTrafficAction("blue")); // "Light malfunction"💡 Pro Tip:
Order your conditions from most specific to least specific, or from most likely to least likely for better performance.
Nested If Statements
You can put if statements inside other if statements to check multiple levels of conditions.
// Simple nesting
let age = 25;
let hasLicense = true;
if (age >= 18) {
if (hasLicense) {
console.log("You can drive");
} else {
console.log("You need a license");
}
} else {
console.log("You're too young");
}
// Output: "You can drive"
// Multiple levels
let isMember = true;
let purchaseAmount = 150;
let hasCode = true;
if (isMember) {
if (purchaseAmount >= 100) {
if (hasCode) {
console.log("20% discount"); // This executes
} else {
console.log("10% discount");
}
} else {
console.log("5% discount");
}
} else {
console.log("No discount");
}
// Output: "20% discount"Refactoring Nested Conditions
// Nested (harder to read)
if (age >= 18) {
if (hasLicense) {
if (hasInsurance) {
console.log("Can drive");
} else {
console.log("Need insurance");
}
} else {
console.log("Need license");
}
} else {
console.log("Too young");
}
// Better: Use logical operators
if (age < 18) {
console.log("Too young");
} else if (!hasLicense) {
console.log("Need license");
} else if (!hasInsurance) {
console.log("Need insurance");
} else {
console.log("Can drive");
}
// Or combine conditions
if (age >= 18 && hasLicense && hasInsurance) {
console.log("Can drive");
} else {
console.log("Requirements not met");
}Best Practice: Try to limit nesting to 2-3 levels. Deep nesting makes code hard to read. Consider using logical operators (&&, ||) or early returns instead.
Common If/Else Patterns
Early Return Pattern
// Instead of nesting:
function processOrder(order) {
if (order) {
if (order.items.length > 0) {
if (order.total > 0) {
// Process order
console.log("Processing order");
}
}
}
}
// Use early returns:
function processOrderBetter(order) {
// Check invalid cases first and return early
if (!order) {
console.log("No order");
return;
}
if (order.items.length === 0) {
console.log("Empty order");
return;
}
if (order.total <= 0) {
console.log("Invalid total");
return;
}
// Main logic at the end, unindented
console.log("Processing order");
}Guard Clauses
function divide(a, b) {
// Guard clause: check for invalid input first
if (b === 0) {
return "Cannot divide by zero";
}
// Main logic
return a / b;
}
function greetUser(user) {
// Guard clauses at the top
if (!user) {
return "No user provided";
}
if (!user.name) {
return "User has no name";
}
// Happy path
return `Hello, ${user.name}!`;
}
console.log(greetUser(null)); // "No user provided"
console.log(greetUser({})); // "User has no name"
console.log(greetUser({ name: "John" })); // "Hello, John!"Default Value Pattern
function createUser(name, role) {
// Set default if not provided
if (!role) {
role = "user";
}
return {
name: name,
role: role
};
}
// Or use short-circuit evaluation
function createUserBetter(name, role) {
role = role || "user";
return {
name: name,
role: role
};
}
console.log(createUser("John")); // { name: "John", role: "user" }
console.log(createUser("Jane", "admin")); // { name: "Jane", role: "admin" }Common Mistakes and How to Avoid Them
1. Assignment Instead of Comparison
let x = 5;
// WRONG: Using = (assignment)
if (x = 10) {
console.log("This always executes!");
}
// x is now 10!
// RIGHT: Using === (comparison)
if (x === 10) {
console.log("x equals 10");
}2. Floating Point Comparison
// WRONG: Direct comparison
let num = 0.1 + 0.2;
if (num === 0.3) {
console.log("Equal"); // Won't execute!
}
console.log(num); // 0.30000000000000004
// RIGHT: Use tolerance
let tolerance = 0.0001;
if (Math.abs(num - 0.3) < tolerance) {
console.log("Close enough!"); // Executes
}3. String Comparison Case Sensitivity
let input = "YES";
// WRONG: Case-sensitive
if (input === "yes") {
console.log("Confirmed"); // Won't execute
}
// RIGHT: Convert to same case
if (input.toLowerCase() === "yes") {
console.log("Confirmed"); // Executes
}4. Checking for Undefined/Null
let value = 0;
// WRONG: Truthy check when you want to check for existence
if (value) {
console.log("Has value"); // Won't execute! 0 is falsy
}
// RIGHT: Explicit check
if (value !== undefined && value !== null) {
console.log("Has value"); // Executes
}
// Or check type
if (typeof value === "number") {
console.log("Has value"); // Executes
}5. Missing Else Block
let status;
let age = 15;
// WRONG: Variable might be undefined
if (age >= 18) {
status = "adult";
}
// What if age < 18? status is undefined!
// RIGHT: Always set a value
if (age >= 18) {
status = "adult";
} else {
status = "minor";
}
console.log(status); // "minor"Practical Examples
Example 1: Login Validation
function validateLogin(username, password) {
// Check if fields are filled
if (!username || !password) {
return "Please fill in all fields";
}
// Check username length
if (username.length < 3) {
return "Username too short";
}
// Check password length
if (password.length < 8) {
return "Password must be at least 8 characters";
}
// All checks passed
return "Valid credentials";
}
console.log(validateLogin("", "pass123"));
// "Please fill in all fields"
console.log(validateLogin("ab", "password123"));
// "Username too short"
console.log(validateLogin("john", "pass"));
// "Password must be at least 8 characters"
console.log(validateLogin("john", "password123"));
// "Valid credentials"Example 2: Discount Calculator
function calculateDiscount(total, isMember, firstPurchase) {
let discount = 0;
// Members get discount
if (isMember) {
if (total >= 100) {
discount = 0.2; // 20% for large purchases
} else {
discount = 0.1; // 10% for regular purchases
}
} else if (firstPurchase) {
discount = 0.15; // 15% for first-time customers
} else if (total >= 200) {
discount = 0.05; // 5% for large non-member purchases
}
let discountAmount = total * discount;
let finalTotal = total - discountAmount;
return {
original: total,
discount: (discount * 100) + "%",
discountAmount: discountAmount.toFixed(2),
finalTotal: finalTotal.toFixed(2)
};
}
console.log(calculateDiscount(150, true, false));
// { original: 150, discount: "20%", discountAmount: "30.00", finalTotal: "120.00" }
console.log(calculateDiscount(80, false, true));
// { original: 80, discount: "15%", discountAmount: "12.00", finalTotal: "68.00" }Example 3: BMI Calculator
function calculateBMI(weight, height) {
// Validate input
if (weight <= 0 || height <= 0) {
return "Invalid input";
}
// Calculate BMI
let bmi = weight / (height * height);
let category;
// Determine category
if (bmi < 18.5) {
category = "Underweight";
} else if (bmi < 25) {
category = "Normal weight";
} else if (bmi < 30) {
category = "Overweight";
} else {
category = "Obese";
}
return {
bmi: bmi.toFixed(1),
category: category
};
}
console.log(calculateBMI(70, 1.75));
// { bmi: "22.9", category: "Normal weight" }
console.log(calculateBMI(90, 1.75));
// { bmi: "29.4", category: "Overweight" }If/Else Practice
Experiment with conditional logic
console.log() to see your output in the console above.Key Takeaways
ifstatements execute code only when condition is trueelseprovides alternative code when condition is falseelse ifchecks multiple conditions in sequence- Only the first true condition in an if/else if chain executes
- Always use
===for comparisons, not= - Always use curly braces
{}even for single statements - Avoid deep nesting—use early returns or logical operators instead
- Order conditions from most specific to least specific
- Use guard clauses to handle invalid cases early
- Test edge cases: empty values, zero, negative numbers, etc.
What's Next?
You now know how to make your programs make decisions using if/else statements! Conditional logic is fundamental to programming—you'll use it in virtually every program you write.
In the next lesson, we'll learn about Switch Statements—an alternative to long if/else if chains that's cleaner when checking a single value against many possible options. Perfect for handling menu selections, days of the week, or status codes!
💪 Practice Challenge:
Before moving on, try creating:
- A function that determines if a year is a leap year
- A movie rating system (G, PG, PG-13, R) based on age
- A shipping cost calculator based on weight and distance
- A username validator that checks multiple requirements
- A grade calculator that accounts for extra credit
Test Your Understanding
What will this code output?
let age = 15;
if (age >= 18) {
console.log('Adult');
}