Conditional Statements: Teaching Programs to Make Decisions
Every morning when you wake up, you decide what to wear based on the weather: if it's raining, take an umbrella; if it's cold, wear a jacket; if the weather is nice, wear a t-shirt. This "if...then..." decision-making process is implemented in programming through conditional statements. Conditional statements are the "brain" of programs, allowing code to respond differently based on different situations.
What Are Conditional Statements
Conditional statements allow programs to decide which code to execute based on whether specific conditions are true or false. Like a fork in the road, programs choose different paths based on road signs (conditions). In JavaScript, the most basic conditional statement is the if statement.
When you write an if statement, you're actually telling the program: "Check this condition, if it's true, execute this code; if it's false, skip it." This process is very intuitive, similar to how humans think.
Basic If Statements
The simplest if statement includes only one condition and one code block:
let temperature = 28;
if (temperature > 25) {
console.log("Today is hot, wear light clothes!");
}In this example, the program checks if the temperature is greater than 25 degrees. If so, it outputs a suggestion to wear light clothes. If the temperature doesn't exceed 25 degrees, this output statement is completely skipped, and the program continues with the following code.
The conditional expression (temperature > 25) is evaluated to a boolean value true or false. Only when the result is true will the code inside the curly braces execute. The curly braces {} define a code block, which is the execution scope of the conditional statement.
If the conditional statement contains only one line of code, you can technically omit the curly braces:
if (temperature > 25) console.log("It's hot!");But this writing style is not recommended because it can lead to errors if you need to add more code later. Always using curly braces is a good habit that makes code clearer and more maintainable.
If-Else Statements: Choose One of Two
In reality, many decisions aren't about "do or not do" but "do this or do that." For example, if it's raining, take an umbrella; otherwise, don't take one. This requires if-else statements:
let isRaining = true;
if (isRaining) {
console.log("Take an umbrella!");
} else {
console.log("Enjoy the sunshine!");
}The else branch defines the code to execute when the condition is false. Whether isRaining is true or false, the program will execute one of the branches—not both, and not neither. This "either-or" structure is very common in programming.
Let's look at a more practical example to check if a user has permission to access a feature:
let userAge = 16;
let canVote = false;
if (userAge >= 18) {
canVote = true;
console.log("You are eligible to vote.");
} else {
canVote = false;
console.log("You are not old enough to vote yet.");
}
console.log(`Voting status: ${canVote}`); // Voting status: falseElse If: Multiple Condition Testing
When you need to check multiple mutually exclusive conditions, else if comes into play. Imagine a grade rating system that gives different grades based on different score ranges:
let score = 85;
let grade;
if (score >= 90) {
grade = "A";
console.log("Excellent work!");
} else if (score >= 80) {
grade = "B";
console.log("Good job!");
} else if (score >= 70) {
grade = "C";
console.log("You passed.");
} else if (score >= 60) {
grade = "D";
console.log("You need improvement.");
} else {
grade = "F";
console.log("You failed. Please study harder.");
}
console.log(`Your grade is: ${grade}`); // Your grade is: BThe key point here is that conditions are checked in order. Once the first true condition is found, the corresponding code block is executed, and then all remaining else if and else branches are skipped. In the above example, although score >= 80, score >= 70, and other conditions are also true, because score >= 90 is false and score >= 80 is first true, only the second branch is executed.
The order of conditions is important. If you write the conditions in reverse, the program's behavior will be completely different:
let score = 85;
// ❌ Wrong order
if (score >= 60) {
console.log("You need improvement."); // This will be executed
} else if (score >= 70) {
console.log("You passed.");
} else if (score >= 80) {
console.log("Good job!");
} else if (score >= 90) {
console.log("Excellent work!");
}In this wrong example, because 85 is greater than 60, the first condition is true, and the program won't check the more specific conditions that follow. So when using else if chains, start checking from the most strict conditions, or use independent if statements.
Nested Conditional Statements
Sometimes, you need to check another condition after one condition is met. This is where nested conditional statements come in. For example, a membership system might need to check both whether a user is logged in and whether they are a premium member:
let isLoggedIn = true;
let isPremiumMember = true;
if (isLoggedIn) {
console.log("Welcome back!");
if (isPremiumMember) {
console.log("You have access to premium features.");
} else {
console.log("Upgrade to premium for more features!");
}
} else {
console.log("Please log in to continue.");
}Although nested conditions are powerful, too-deep nesting can make code difficult to read and maintain. When nesting levels exceed 2-3 layers, you should consider refactoring the code. A common improvement is using logical operators && (AND) and || (OR):
let isLoggedIn = true;
let isPremiumMember = true;
// Simplified using logical AND operator
if (isLoggedIn && isPremiumMember) {
console.log("Welcome back! You have access to premium features.");
} else if (isLoggedIn && !isPremiumMember) {
console.log("Welcome back! Upgrade to premium for more features.");
} else {
console.log("Please log in to continue.");
}Another technique is "early return," especially in functions:
function checkAccess(isLoggedIn, isPremiumMember) {
// Early return to reduce nesting
if (!isLoggedIn) {
return "Please log in to continue.";
}
if (!isPremiumMember) {
return "Upgrade to premium for more features!";
}
return "You have access to premium features.";
}
console.log(checkAccess(true, true)); // You have access to premium features.
console.log(checkAccess(true, false)); // Upgrade to premium for more features!
console.log(checkAccess(false, false)); // Please log in to continue.Ternary Operator: Concise Conditional Expression
For simple one-or-the-other scenarios, JavaScript provides a more concise syntax: the ternary operator (also called conditional operator). Its syntax is condition ? value1 : value2, meaning "if condition is true, return value 1, otherwise return value 2."
let age = 20;
let status = age >= 18 ? "adult" : "minor";
console.log(status); // adultThis is equivalent to:
let age = 20;
let status;
if (age >= 18) {
status = "adult";
} else {
status = "minor";
}The ternary operator is especially suitable for assignment or direct use in expressions:
let temperature = 15;
console.log(`It's ${temperature > 20 ? "warm" : "cool"} today.`);
// Using in function parameters
function greet(name, timeOfDay) {
console.log(
`Good ${timeOfDay === "morning" ? "morning" : "evening"}, ${name}!`
);
}
greet("Alice", "morning"); // Good morning, Alice!
greet("Bob", "evening"); // Good evening, Bob!However, don't overuse the ternary operator. Nested ternary operators can make code difficult to understand:
// ❌ Hard-to-read nested ternary operator
let score = 85;
let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";
// ✅ This case should use if-else if
let score = 85;
let grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "F";
}Truthy and Falsy Values
In conditional statements, JavaScript converts conditional expressions to boolean values. But not all values need to be explicitly true or false. In JavaScript, some values are considered "falsy" in boolean contexts, while all other values are considered "truthy."
There are only 7 falsy values: false, 0, -0, 0n (BigInt zero), "" (empty string), null, undefined, and NaN.
// These will all enter the else branch
if (0) {
console.log("Won't print");
} else {
console.log("0 is falsy"); // This will execute
}
if ("") {
console.log("Won't print");
} else {
console.log("Empty string is falsy"); // This will execute
}
if (null) {
console.log("Won't print");
} else {
console.log("null is falsy"); // This will execute
}
// All other values are truthy
if ("hello") {
console.log("Non-empty string is truthy"); // This will execute
}
if (42) {
console.log("Non-zero number is truthy"); // This will execute
}
if ([]) {
console.log("Empty array is truthy"); // This will execute!
}
if ({}) {
console.log("Empty object is truthy"); // This will execute!
}This feature is convenient but can also lead to errors. A common pitfall is that empty arrays and empty objects are truthy:
let items = [];
if (items) {
console.log("This will run even though array is empty!");
}
// Correct way to check
if (items.length > 0) {
console.log("Array has items");
} else {
console.log("Array is empty");
}Practical Application Scenarios
1. Form Validation
Conditional statements are very common in form validation:
function validateEmail(email) {
if (!email) {
return "Email is required";
}
if (!email.includes("@")) {
return "Invalid email format";
}
if (email.length < 5) {
return "Email is too short";
}
return "Email is valid";
}
console.log(validateEmail("")); // Email is required
console.log(validateEmail("invalid")); // Invalid email format
console.log(validateEmail("a@b")); // Email is too short
console.log(validateEmail("[email protected]")); // Email is valid2. User Permission Checks
function canDeletePost(user, post) {
// Admins can delete any post
if (user.role === "admin") {
return true;
}
// Moderators can delete posts in their section
if (user.role === "moderator" && post.category === user.moderatedCategory) {
return true;
}
// Users can only delete their own posts
if (post.authorId === user.id) {
return true;
}
return false;
}
let adminUser = { id: 1, role: "admin" };
let regularUser = { id: 2, role: "user" };
let post = { id: 100, authorId: 3, category: "tech" };
console.log(canDeletePost(adminUser, post)); // true
console.log(canDeletePost(regularUser, post)); // false3. Responsive Design
function getDeviceType() {
let width = window.innerWidth;
if (width < 768) {
return "mobile";
} else if (width < 1024) {
return "tablet";
} else {
return "desktop";
}
}
function adjustLayout() {
let deviceType = getDeviceType();
if (deviceType === "mobile") {
console.log("Show mobile menu");
console.log("Use single column layout");
} else if (deviceType === "tablet") {
console.log("Show tablet menu");
console.log("Use two column layout");
} else {
console.log("Show full menu");
console.log("Use three column layout");
}
}4. API Response Handling
function handleAPIResponse(response) {
if (response.status === 200) {
console.log("Success:", response.data);
return response.data;
} else if (response.status === 404) {
console.log("Error: Resource not found");
return null;
} else if (response.status === 500) {
console.log("Error: Server error");
return null;
} else {
console.log("Error: Unknown error");
return null;
}
}Common Pitfalls and Best Practices
1. Use === Instead of ==
JavaScript has two equality comparison operators: == (loose equality) and === (strict equality). == performs type conversion, which can lead to unexpected results:
// ❌ Using == can lead to unexpected behavior
if (0 == false) {
console.log("This is true!"); // Will execute
}
if ("" == false) {
console.log("This is also true!"); // Will execute
}
// ✅ Using === is safer
if (0 === false) {
console.log("Won't execute");
}
if ("5" === 5) {
console.log("Won't execute");
}
if ("5" == 5) {
console.log("Will execute with =="); // Will execute
}In almost all cases, you should use === and !==, unless you explicitly need type conversion.
2. Avoid Overly Long Condition Chains
When else if chains become too long, consider using other approaches:
// ❌ Overly long else if chain
function getColorName(code) {
if (code === "#FF0000") {
return "Red";
} else if (code === "#00FF00") {
return "Green";
} else if (code === "#0000FF") {
return "Blue";
} else if (code === "#FFFF00") {
return "Yellow";
} else if (code === "#FF00FF") {
return "Magenta";
} else {
return "Unknown";
}
}
// ✅ Use object lookup
function getColorName(code) {
const colorMap = {
"#FF0000": "Red",
"#00FF00": "Green",
"#0000FF": "Blue",
"#FFFF00": "Yellow",
"#FF00FF": "Magenta",
};
return colorMap[code] || "Unknown";
}3. Clear Conditional Expressions
Avoid relying on implicit truthy/falsy conversion, especially when conditions aren't obvious:
// ❌ Not clear
let count = 0;
if (count) {
console.log("Has items");
}
// ✅ Clear intent
if (count > 0) {
console.log("Has items");
}
// ❌ Not clear
let user = null;
if (!user) {
console.log("No user");
}
// ✅ More explicit
if (user === null || user === undefined) {
console.log("No user");
}4. Handle Edge Cases
Always consider edge cases and exceptional inputs:
function getDiscount(age) {
// ✅ Handle invalid input
if (typeof age !== "number" || age < 0) {
return 0;
}
if (age < 12) {
return 0.5; // Children get half price
} else if (age >= 65) {
return 0.3; // Seniors get 30% off
} else {
return 0; // No discount
}
}
console.log(getDiscount(-5)); // 0
console.log(getDiscount("young")); // 0
console.log(getDiscount(10)); // 0.5
console.log(getDiscount(70)); // 0.3Summary
Conditional statements are one of the fundamental building blocks of programming, allowing programs to make decisions based on different situations. Mastering the use of if, else if, else, and ternary operators, understanding the concepts of truthy and falsy values, will help you write more flexible and intelligent code.
Key points:
- Use
ifstatements to execute conditional code else ifcan chain multiple mutually exclusive conditions- Ternary operators are suitable for simple one-or-the-other scenarios
- Always use
===for comparisons - Pay attention to condition order and edge cases
- Keep code clear and avoid excessive nesting
- Consider using object lookup or other patterns to replace overly long condition chains
Understanding and skillfully using conditional statements is the first step to becoming an excellent programmer. As you gain practice, you'll become increasingly adept at building complex program logic with conditional statements.