Review Examples For Conditionals¶
Conditionals Explainer¶
Conditional statements in JavaScript are a fundamental part of programming, essential for controlling the flow of a program. They allow your code to make decisions and execute different actions based on certain conditions, much like the decision-making processes we use in everyday life. Understanding how conditionals influence the program flow is key for beginners to build dynamic and interactive web applications. Here's a simple guide:
The Basic if
Statement¶
The if
statement is the most basic form of conditional. It performs a block of code if a specified condition is true.
if (condition) {
// code to execute if condition is true
}
let age = 25; // age set to 25, which is greater than 18
if (age > 18) {
console.log("You are an adult.");
}
Now, let's change the value being stored in the age
variable to 16
. What do you think will be printed to the console after we make this change? (Hint: This is a trick question!)
age = 16 // reassign the value stored in 'age variable'
if (age > 18) {
console.log("You are an adult.");
}
The if... else
Statement¶
The if...else
statement in JavaScript allows for two possible paths of execution: the code within the if block runs if the specified condition evaluates to true, and the code within the else block runs if the condition evaluates to false.
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
let temperature = 20;
// Simple if...else statement to check temperature
if (temperature > 25) {
console.log("It's warm outside.");
} else {
console.log("It's not warm outside.");
}
The if... else if... else
Statement¶
The if... else if... else
statement in JavaScript is used when you have multiple conditions to check and want different code executed for each specific condition. Theif
block runs for the first true conditelse if
allows checking additional conditions, the else
covers all remaining scenarios where none of the previous conditions are met.
if (condition) {
// code if condition is true
} else if(condition) {
// code if condition is false
} else {
// code if condition is false
}
let score = 70;
// Using if...else if...else to categorize the score
if (score >= 90) {
console.log("Excellent!");
} else if (score >= 75) {
console.log("Good job!");
} else {
console.log("Needs improvement.");
}
The Switch Statement¶
Have a lot of conditions that you need to check? The switch statement in JavaScript is used to execute different code blocks based on the value of a variable or expression. It's a more structured and readable alternative to multiple if...else if
statements, especially when comparing the same variable or expression against various values. Here is an example:
let dayOfWeek = "Tuesday";
switch (dayOfWeek) {
case "Monday":
console.log("It's Monday, the start of the week.");
break;
case "Tuesday":
console.log("It's Tuesday, the second day of the week.");
break;
case "Wednesday":
console.log("It's Wednesday, the middle of the week.");
break;
case "Thursday":
console.log("It's Thursday, one more day to Friday.");
break;
case "Friday":
console.log("It's Friday, the weekend is near.");
break; case "Saturday":
case "Sunday":
console.log("It's the weekend!");
break;
default:
console.log("Not a valid day.");
}
Switch statements in JavaScript are straightforward for handling multiple conditions based on a single variable or expression, but they have their quirks. One common criticism is the "fall-through" behavior: if you forget to include a break
statement after each case, the code will continue executing the next cases until it hits a break
, leading to unexpected results. This behavior, while useful in certain scenarios, often requires extra caution and can introduce bugs if not managed carefully. Additionally, switch
is less flexible than if...else if
structures, as it only tests for strict equality (===
) and doesn't handle more complex conditions or logical operators. This limitation can make switch
less suitable for more nuanced decision-making processes in code.
Nested Conditionals¶
You can nest if
statements within each other. This means you can have an if
or else if
statement inside another if
or else if
statement.
Nested conditionals are used when you need to make a decision that depends on multiple conditions being met. They are useful for handling complex decision-making processes where one condition must be true before another condition is even considered. However, they should be used judiciously to maintain code readability.
let age = 20;
let hasLicense = true;
// Outer if statement
if (age >= 18) {
// Nested if statement
if (hasLicense) {
console.log("You are an adult and have a driver's license.");
} else {
console.log("You are an adult but don't have a driver's license.");
}
} else {
console.log("You are not an adult yet.");
}
if (age > 18) {
if (isStudent) {
console.log("You are an adult student.");
} else {
console.log("You are an adult.");
}
} else {
console.log("You are a minor.");
}
Understanding and effectively using conditional statements is crucial in programming. They are the building blocks for creating responsive, flexible, and robust applications. By mastering how to control program flow with conditionals, you equip yourself to tackle more complex programming challenges.
Let's put together what we have learned about Conditional Statement with our previous lessons on Operators, Variables, etc. Here are some more comjplex examples:
let number1 = 5;
let number2 = 10;
// Check if both variables are of type 'number' and if their sum is greater than 10
if (typeof number1 === 'number' && typeof number2 === 'number' && (number1 + number2) > 10) {
console.log("Both are numbers and their sum is greater than 10.");
} else {
console.log("Condition not met.");
}
let age = 30;
let isEmployed = true;
// Check if the person is over 25 years old and employed
if (age > 25 && isEmployed === true) {
console.log("The person is over 25 years old and employed.");
} else {
console.log("The condition is not met.");
}
let temperature = 22;
let weatherType = "sunny";
// Check if the temperature is below 25 and the weather is sunny
if (temperature < 25 && weatherType === "sunny") {
console.log("It's a pleasant sunny day with moderate temperature.");
} else {
console.log("The conditions are not ideal.");
}
// Declaring variables using let and const
const maxScore = 100;
let studentScore = 87;
let grade;
// Using arithmetic operation to calculate percentage
let percentage = (studentScore / maxScore) * 100;
// Using comparison and logical operators in a complex if...else if structure
if (percentage >= 90) {
grade = "A";
} else if (percentage >= 80 && percentage < 90) {
grade = "B";
} else if (percentage >= 70 && percentage < 80) {
grade = "C";
} else if (percentage >= 60 && percentage < 70) {
grade = "D";
} else {
grade = "F";
}
// Using the typeof keyword to check the data type of 'grade'
console.log("Grade type:", typeof grade);
// Final output
console.log(`The student scored ${percentage}% which is a grade: ${grade}`);
// Declare variables using let and const
const MAX_CAPACITY = 100;
let currentAttendance = 75;
let weatherCondition = "sunny";
let temperature = 22;
// Arithmetic operation
let remainingCapacity = MAX_CAPACITY - currentAttendance;
// Using logical, comparison operators, and typeof
if (typeof weatherCondition === "string" && weatherCondition === "sunny" && temperature > 20 && remainingCapacity > 25) {
console.log("Great day for an outdoor event. Spots still available!");
} else if (typeof weatherCondition === "string" && (weatherCondition === "rainy" || temperature <= 20) && remainingCapacity <= 25) {
console.log("Event is happening but with limited capacity indoors due to weather.");
}
let userAge = 30;
const legalDrinkingAge = 21;
let userLocation = "USA";
const drinkingAgeInUSA = 21;
// Check if the user's age is greater than or equal to the legal drinking age
if (userAge >= legalDrinkingAge) {
console.log("User is legally allowed to drink.");
// Nested if: Further check if the user is in the USA and meets the specific drinking age requirement
if (userLocation === "USA" && userAge >= drinkingAgeInUSA) {
console.log("User can legally drink in the USA.");
} else {
console.log("User can legally drink, but not in the USA.");
}
} else {
console.log("User is not legally allowed to drink.");
}
Already, we are writing quite complex code structures! Don't worry about memorizing all these different forms of conditionals (or program flow, as it is also referred to) and focus on understanding what they are used for. You can always look up the specifics of syntax as you go.
Practice Problems¶
Coming Soon!
Practice with AI¶
Coming Soon!