JavaScript If Else
In programming, we often need to execute different code blocks based on certain conditions. JavaScript's if
, else if
, and else
statements provide a way to make these decisions in our code, creating branches in our program's execution flow.
Introduction to Conditional Statements
Conditional statements allow your code to make decisions and execute different actions based on different conditions. These are fundamental to creating dynamic, interactive programs that can respond to user input, data changes, or system events.
The if
Statement
The if
statement is the most basic conditional statement. It executes a block of code only if a specified condition evaluates to true
.
Basic Syntax
if (condition) {
// code to execute if condition is true
}
Example
const hour = 14;
if (hour < 18) {
console.log("Good day!");
}
// Output: "Good day!"
In this example, the message "Good day!" is displayed because the condition hour < 18
is true (14 is less than 18).
The if...else
Statement
Often, you want to execute one block of code if a condition is true and another block if the condition is false. This is where the if...else
statement comes in.
Basic Syntax
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
Example
const hour = 20;
if (hour < 18) {
console.log("Good day!");
} else {
console.log("Good evening!");
}
// Output: "Good evening!"
Here, because hour < 18
is false (20 is not less than 18), the else
block executes and outputs "Good evening!".
The if...else if...else
Statement
For multiple conditions, use the if...else if...else
structure. This allows you to check multiple conditions in sequence.
Basic Syntax
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition1 is false and condition2 is true
} else {
// code to execute if both condition1 and condition2 are false
}
Example
const hour = 14;
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
// Output: "Good afternoon!"
In this case, hour < 12
is false (14 is not less than 12), but hour < 18
is true (14 is less than 18), so "Good afternoon!" is displayed.
Nested if
Statements
You can also nest if
statements inside other if
or else
blocks to create more complex decision trees.
Example
const x = 15;
const y = 10;
if (x > 10) {
console.log("x is greater than 10");
if (y > 5) {
console.log("and y is greater than 5");
}
}
// Output:
// "x is greater than 10"
// "and y is greater than 5"
This executes both messages because both conditions are true.
Ternary Operator: A Shorthand for if...else
For simple if...else
statements, JavaScript offers a condensed syntax called the ternary operator.
Basic Syntax
condition ? expressionIfTrue : expressionIfFalse;
Example
const age = 20;
const canVote = age >= 18 ? "Yes" : "No";
console.log(canVote);
// Output: "Yes"
This is equivalent to:
let canVote;
if (age >= 18) {
canVote = "Yes";
} else {
canVote = "No";
}
Real-World Applications
Let's explore some practical examples of using conditional statements in real-world scenarios.
User Authentication
function checkAccess(username, password) {
const validUsername = "user123";
const validPassword = "pass456";
if (username === validUsername && password === validPassword) {
return "Access granted!";
} else if (username === validUsername) {
return "Incorrect password!";
} else {
return "Invalid username!";
}
}
console.log(checkAccess("user123", "pass456")); // Output: "Access granted!"
console.log(checkAccess("user123", "wrongpass")); // Output: "Incorrect password!"
console.log(checkAccess("wrong", "pass456")); // Output: "Invalid username!"
Shopping Cart Discount
function calculateDiscount(cartTotal, userType) {
if (userType === "premium") {
return cartTotal * 0.2; // 20% discount for premium users
} else if (cartTotal > 100) {
return cartTotal * 0.1; // 10% discount for orders above $100
} else {
return 0; // No discount
}
}
console.log(calculateDiscount(120, "regular")); // Output: 12 (10% of 120)
console.log(calculateDiscount(80, "premium")); // Output: 16 (20% of 80)
console.log(calculateDiscount(50, "regular")); // Output: 0 (no discount)
Weather Advice App
function getWeatherAdvice(temperature) {
if (temperature > 30) {
return "It's hot! Remember to stay hydrated.";
} else if (temperature > 20) {
return "Nice weather today!";
} else if (temperature > 10) {
return "Better take a light jacket.";
} else if (temperature > 0) {
return "It's cold, wear a warm coat!";
} else {
return "Freezing temperatures! Stay warm!";
}
}
console.log(getWeatherAdvice(35)); // Output: "It's hot! Remember to stay hydrated."
console.log(getWeatherAdvice(15)); // Output: "Better take a light jacket."
console.log(getWeatherAdvice(-5)); // Output: "Freezing temperatures! Stay warm!"
Best Practices for Using Conditional Statements
-
Keep conditions simple: Complex conditions can be hard to read and maintain. Consider breaking them down or using intermediate variables.
-
Use comparison operators wisely: Understanding the difference between
==
(equality) and===
(strict equality) is important. -
Avoid deep nesting: Deeply nested
if
statements can lead to "spaghetti code." Consider restructuring or using switch statements where appropriate. -
Use curly braces consistently: Even for single-line blocks, using curly braces improves readability and prevents bugs.
-
Be cautious with truthy/falsy evaluations: JavaScript evaluates expressions as either truthy or falsy, which can lead to unexpected results.
// Avoid this:
if (value) {
// This will execute for any truthy value, not just true
}
// Prefer explicit comparisons:
if (value === true) {
// This will only execute if value is boolean true
}
Summary
Conditional statements are essential tools in programming that allow your code to make decisions and execute different paths based on conditions:
- Use
if
statements to execute code when a condition is true - Use
if...else
to handle two possible outcomes - Use
if...else if...else
for multiple conditions - The ternary operator provides a shorthand for simple if-else decisions
- Nested conditionals allow for complex decision-making but should be used carefully
By mastering conditional statements, you gain the ability to create more dynamic and responsive JavaScript applications that can adapt to different scenarios and user inputs.
Practice Exercises
-
Write a function that determines whether a number is positive, negative, or zero.
-
Create a simple grading system that converts numerical scores (0-100) to letter grades (A, B, C, D, F).
-
Build a function that calculates ticket prices based on age (child, adult, senior) and day of the week (weekday vs. weekend).
-
Implement a simple login system that checks username and password combinations.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)