JavaScript Conditional Statements
In programming, we often need to make decisions based on certain conditions. JavaScript provides several ways to implement decision-making in your code, known as conditional statements. These statements allow your program to perform different actions depending on whether a specific condition evaluates to true or false.
Introduction to Conditional Statements
Conditional statements are essential building blocks in programming that enable your code to make decisions and execute different actions based on different inputs. They allow your programs to be flexible, responsive, and capable of handling various scenarios.
In JavaScript, there are three main types of conditional statements:
if
statementsif...else
statementsswitch
statements
Let's explore each of these in detail.
The if
Statement
The if
statement is the simplest form of conditional statement. It executes a block of code only when the specified condition is true.
Basic Syntax
if (condition) {
// code to be executed if the condition is true
}
How It Works
- First, the condition inside the parentheses is evaluated
- If the condition is true, the code block inside the curly braces
{}
is executed - If the condition is false, the code block is skipped entirely
Example
const temperature = 28;
if (temperature > 25) {
console.log("It's a hot day!");
}
// Output: It's a hot day!
In this example, since the temperature (28) is greater than 25, the condition is true, and the message is printed to the console.
The if...else
Statement
The if...else
statement extends the basic if
statement by providing an alternative code block to execute when the condition is false.
Basic Syntax
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Example
const hour = 20;
if (hour < 18) {
console.log("Good day!");
} else {
console.log("Good evening!");
}
// Output: Good evening!
In this example, since the hour (20) is not less than 18, the condition is false, so the code in the else
block is executed.
The if...else if...else
Statement
When you need to check multiple conditions, you can chain several if...else
statements together using else if
.
Basic Syntax
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition1 is false and condition2 is true
} else {
// code to be executed if both condition1 and condition2 are false
}
Example
const score = 75;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else if (score >= 60) {
console.log("Grade: D");
} else {
console.log("Grade: F");
}
// Output: Grade: C
In this example, the program checks multiple score ranges and assigns a grade accordingly. Since the score is 75, it falls into the "Grade: C" condition.
Ternary Operator
The ternary operator provides a concise way to write simple conditional statements. It's often used for assigning values based on a condition.
Basic Syntax
condition ? expressionIfTrue : expressionIfFalse
Example
const age = 20;
const canVote = age >= 18 ? "Yes" : "No";
console.log(`Can the person vote? ${canVote}`);
// Output: Can the person vote? Yes
In this example, since age (20) is greater than or equal to 18, the ternary operator evaluates to "Yes".
The switch
Statement
The switch
statement provides a way to handle multiple possible conditions for a single variable. It can be more readable than multiple if...else
statements when checking the same variable against different values.
Basic Syntax
switch (expression) {
case value1:
// code to execute if expression === value1
break;
case value2:
// code to execute if expression === value2
break;
// more cases as needed
default:
// code to execute if none of the cases match
}
How It Works
- The
switch
expression is evaluated once - The value of the expression is compared with the values of each
case
- If there's a match, the associated block of code is executed
- The
break
statement exits the switch block - The
default
statement is optional and executes if no case match is found
Example
const day = new Date().getDay();
let dayName;
switch (day) {
case 0:
dayName = "Sunday";
break;
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:
dayName = "Saturday";
break;
default:
dayName = "Unknown Day";
}
console.log(`Today is ${dayName}`);
// Output depends on the current day
Multiple Cases with Same Action
You can group cases when you want the same action for multiple values:
const fruit = "Apple";
let category;
switch (fruit) {
case "Apple":
case "Orange":
case "Banana":
category = "Regular fruit";
break;
case "Mango":
case "Pineapple":
category = "Tropical fruit";
break;
default:
category = "Unknown fruit";
}
console.log(`${fruit} is a ${category}`);
// Output: Apple is a Regular fruit
Practical Examples
Example 1: Simple Authentication
function login(username, password) {
const correctUsername = "user123";
const correctPassword = "pass456";
if (username === correctUsername && password === correctPassword) {
return "Login successful!";
} else if (username !== correctUsername) {
return "Username incorrect!";
} else {
return "Password incorrect!";
}
}
console.log(login("user123", "pass456")); // Output: Login successful!
console.log(login("user999", "pass456")); // Output: Username incorrect!
console.log(login("user123", "wrongpass")); // Output: Password incorrect!
Example 2: Discount Calculator
function calculateDiscount(purchaseAmount, membershipLevel) {
let discount = 0;
switch (membershipLevel.toLowerCase()) {
case "platinum":
discount = 0.15;
break;
case "gold":
discount = 0.10;
break;
case "silver":
discount = 0.05;
break;
default:
discount = 0;
}
// Additional discount for large purchases
if (purchaseAmount >= 500) {
discount += 0.05;
} else if (purchaseAmount >= 200) {
discount += 0.02;
}
const discountAmount = purchaseAmount * discount;
const finalPrice = purchaseAmount - discountAmount;
return {
originalPrice: purchaseAmount,
discountPercentage: discount * 100,
discountAmount: discountAmount,
finalPrice: finalPrice
};
}
const purchase = calculateDiscount(300, "Gold");
console.log(`Original price: $${purchase.originalPrice}`);
console.log(`Discount: ${purchase.discountPercentage}%`);
console.log(`You saved: $${purchase.discountAmount.toFixed(2)}`);
console.log(`Final price: $${purchase.finalPrice.toFixed(2)}`);
/* Output:
Original price: $300
Discount: 12%
You saved: $36.00
Final price: $264.00
*/
Example 3: Weather App Recommendation
function getWeatherAdvice(temperature, isRaining) {
let advice = "";
if (isRaining) {
advice = "Remember to take an umbrella! ";
}
if (temperature < 0) {
advice += "It's freezing! Wear a heavy coat, gloves, and a hat.";
} else if (temperature < 10) {
advice += "It's cold. Wear a warm coat.";
} else if (temperature < 20) {
advice += "It's cool. A light jacket would be good.";
} else if (temperature < 30) {
advice += "It's warm. A t-shirt should be fine.";
} else {
advice += "It's hot! Stay hydrated and wear sunscreen.";
}
return advice;
}
console.log(getWeatherAdvice(25, false));
// Output: It's warm. A t-shirt should be fine.
console.log(getWeatherAdvice(5, true));
// Output: Remember to take an umbrella! It's cold. Wear a warm coat.
Best Practices for Conditional Statements
-
Keep conditionals simple: Complex conditions can be hard to read and debug. Consider breaking them into smaller, more manageable pieces.
-
Use meaningful variable names: This helps make your conditions more readable.
-
Avoid deeply nested conditionals: Too many nested
if
statements can make code hard to follow. Consider restructuring or using switch statements where appropriate. -
Be careful with equality operators: Use strict equality (
===
) instead of loose equality (==
) to avoid unexpected type conversions. -
Don't forget
break
in switch statements: Forgetting thebreak
statement will cause execution to "fall through" to the next case. -
Consider ternary operators for simple cases: They can make your code more concise, but don't overuse them as they can reduce readability.
Summary
Conditional statements are fundamental building blocks in JavaScript that allow your code to make decisions based on specific conditions:
if
statements execute code when a condition is trueif...else
statements provide an alternative when the condition is falseif...else if...else
chains handle multiple conditions- Ternary operators provide a concise way for simple conditional expressions
switch
statements are ideal for comparing a single value against multiple possible cases
By mastering conditional statements, you've taken a significant step toward writing dynamic and responsive JavaScript programs that can handle various scenarios based on inputs and conditions.
Exercises
-
Write a function that takes a number as input and returns "Positive", "Negative", or "Zero" based on the input value.
-
Create a function that determines whether a year is a leap year. (Hint: a year is a leap year if it's divisible by 4, but not divisible by 100 unless it's also divisible by 400).
-
Write a "rock, paper, scissors" game that takes two player choices and determines the winner using conditional statements.
-
Create a function that converts numerical grades (0-100) to letter grades (A, B, C, D, F) using both if-else chains and switch statements. Compare the two approaches.
Additional Resources
- MDN Web Docs: if...else
- MDN Web Docs: switch
- JavaScript.info: Conditional operators
- W3Schools: JavaScript if, else, and else if
Happy coding!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)