#Day07 - Control Flow - Conditional Statements
Conditional logic in JavaScript: if-else, switch statements and ternary Operators
Control flow is a fundamental part of programming, and you will use it extensively throughout your coding journey. Whether you're writing simple scripts or complex applications, control flow statements like if-else and switch are essential for controlling the flow of execution in your code.
Control flow refers to the order in which code is executed in a program. In JavaScript, there are several control flow statements that allow you to specify the conditions under which certain code blocks should be executed. In this article, we'll take a closer look at two of the most commonly used control flow statements in JavaScript: if-else statements and switch statements. And also we will learn about ternary operators, which is a useful tool for concisely expressing conditional logic.
What are if-else statements?
In JavaScript, if-else statements allow you to specify a condition, and if that condition is true, a block of code will be executed. If the condition is false, you can use an else
clause to specify a different block of code to be executed. Here's the basic syntax for an if-else statement in JavaScript:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
You can also use multiple else if
clauses to test for multiple conditions:
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 condition1 and condition2 are false
}
Examples of if-else statements
Let's look at some examples of how you might use if-else statements in your JavaScript code.
Checking the weather
Imagine you want to write a function that suggests an activity based on the current weather. Here's how you might use an if-else statement to do this:
let weather = "sunny";
if (weather === "sunny") {
console.log("It's a beautiful day! Why not go for a hike or a bike ride?");
} else if (weather === "cloudy") {
console.log("It's a bit overcast today. Maybe it's a good day for a museum or a bookstore?");
} else {
console.log("It's raining or snowing. How about staying in and watching a movie?");
}
In this example, the weather
variable is set to "sunny", and the if-else statement checks if the weather
variable is equal to "sunny". If it is, the code inside the first block is executed. If it is not, the if-else statement checks if the weather
variable is equal to "cloudy". If it is, the code inside the second block is executed. If it is not, the code inside the else
block is executed.
Nested if-else
You can also use if-else statements inside other if-else statements to create nested if-else statements. Nested if-else statements allow you to specify multiple levels of conditions, with each level being tested only if the preceding level is true. Here is an example of a nested if-else statement:
if (condition1) {
// code to be executed if condition1 is true
if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if condition2 is false
}
} else {
// code to be executed if condition1 is false
}
In this example, the inner if-else statement is only executed if condition1
is true. If condition1
is false, the code inside the inner if-else statement is skipped and the code inside the outer else
block is executed.
Nested if-else statements can be useful when you want to test for multiple conditions and execute different code blocks based on the combination of those conditions. However, it's important to be careful when using nested if-else statements, as they can make your code more complex and harder to read.
Combining Multiple Conditions with Comparison and Logical Operators
If-else statements are a powerful tool for controlling the flow of execution in your code, and they allow you to specify different actions based on different conditions. In addition to simple comparisons like ===
and !==
, if-else statements also allow you to use comparison operators like >
, <
, >=
, and <=
to test for ranges of values, and logical operators like &&
and ||
to combine multiple conditions.
Here's an example of using comparison and logical operators in an if-else statement:
let age = 25;
// check if age is greater than or equal to 18 and less than 65
if (age >= 18 && age < 65) {
console.log("You are an adult.");
}
// check if age is greater than or equal to 65
else if (age >= 65) {
console.log("You are a senior citizen.");
}
// if age is not greater than or equal to 18 or 65
else {
console.log("You are a minor.");
}
In this example, the age
variable is set to 25 and the if-else statement tests if the age
is greater than or equal to 18 and less than 65 using the &&
operator. If it is, the code inside the first block is executed. If it is not, the if-else statement tests if the age
is greater than or equal to 65. If it is, the code inside the second block is executed. If it is not, the code inside the else
block is executed.
Switch statements
In addition to if-else statements, JavaScript also provides a control flow statement called a switch
statement. A switch
statement allows you to specify a number of different cases, and the code will execute the case that matches the specified value. Here's the basic syntax for a switch
statement in JavaScript:
switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
default:
// code to be executed if expression doesn't match any of the cases
}
The expression
in a switch
statement is typically a variable or an expression that evaluates to a value. The case
clauses specify the different values that the expression
can be, and the code inside each case
clause is executed if the expression
equals that value. The default
clause specifies code to be executed if the expression
doesn't match any of the case
values.
It's important to note that the break
the statement is used to exit each case
clause and prevent the code in the following cases from being executed. If you omit the break
the statement, the code in all subsequent case
clauses will be executed, regardless of whether the expression
matches those values.
Best practices for using if-else statements
Here are a few best practices to keep in mind when using if-else statements in your JavaScript code:
Use clear, concise conditionals: Make sure your conditions are easy to understand and free of unnecessary complexity.
Avoid nesting if-else statements too deeply: While it's sometimes necessary to nest if-else statements, try to keep your code as flat as possible to avoid creating hard-to-read code.
Test all possible cases: Make sure you've covered all possible cases in your if-else statements, including the
else
clause for cases where none of the conditions are true.Use
else if
clauses sparingly: Whileelse if
clauses can be useful for testing multiple conditions, too many of them can make your code harder to read and maintain.
By following these best practices, you can write clear, readable code that makes use of if-else statements to control the flow of execution in your programs.
Ternary Operators
Ternary operators, also known as conditional operators, are a way to concisely express conditional logic in JavaScript. They are a type of operator that takes three operands: a condition, a result if the condition is true, and a result if the condition is false.
The syntax for a ternary operator in JavaScript is:
result = condition ? value1 : value2;
If the condition
is true, the expression evaluates to value1
; otherwise, it evaluates to value2
.
Here is an example of how you might use a ternary operator in a JavaScript program:
let x = 10;
let y = 20;
let max;
max = (x > y) ? x : y;
In this example, the ternary operator compares the values of x
and y
, and assigns the larger value to max
. If x
is greater than y
, the value of x
is assigned to max
; otherwise, the value of y
is assigned to max
.
Here is an example of how you might rewrite the previous example using an if-else statement:
let x = 10;
let y = 20;
let max;
if (x > y) {
max = x;
} else {
max = y;
}
Both of these examples achieve the same result, but the if-else statement may be easier to understand for readers of your code who are less familiar with ternary operators.
In conclusion, ternary operators can be a useful tool for concisely expressing conditional logic in JavaScript
Conclusion
In summary, if-else statements are a crucial tool for controlling the flow of execution in JavaScript. Whether you're checking the weather, validating user input, or making any other type of a decision, if-else statements can help you write code that executes different actions based on different conditions. And we have also covered the ternary operators - a useful tool for concisely expressing conditional logic. With a little practice and attention to best practices, you can master the use of if-else statements and take your JavaScript skills to the next level.
Thank you for being with me on this journey. I hope you have enjoyed reading these blogs and that you have found them helpful and informative.
Namaste, and thank you for reading!