Conditional Statements
Conditional statements are a fundamental aspect of programming that allow your code to make decisions based on specific conditions. In this lesson, you will learn how to use conditional statements in JavaScript to control the flow of your programs. By the end of this lesson, you'll be able to create dynamic applications that respond to user input and other conditions.
1. What Are Conditional Statements?
Conditional statements are used to perform different actions based on whether a specified condition is true or false. They help you implement logic in your code, allowing it to respond appropriately to different inputs and situations.
Common Conditional Statements in JavaScript:
if
statementif...else
statementelse if
statementswitch
statement
2. The if
Statement
The simplest form of a conditional statement is the if
statement. It executes a block of code if the specified condition evaluates to true
.
Syntax:
if (condition) {
// Code to execute if the condition is true
}
Example:
let temperature = 30;
if (temperature > 25) {
console.log("It's a hot day!"); // This will execute
}
3. The if...else
Statement
The if...else
statement allows you to specify an alternative block of code to execute if the condition is false.
Syntax:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
Example:
let score = 75;
if (score >= 60) {
console.log("You passed!"); // This will execute
} else {
console.log("You failed. Try again!");
}
4. The else if
Statement
The else if
statement lets you check multiple conditions. You can chain multiple else if
statements to test different conditions sequentially.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if all conditions are false
}
Example:
let grade = 85;
if (grade >= 90) {
console.log("A");
} else if (grade >= 80) {
console.log("B"); // This will execute
} else if (grade >= 70) {
console.log("C");
} else {
console.log("D");
}
5. The switch
Statement
The switch
statement is an alternative to using multiple if...else if
statements when evaluating a single expression against multiple possible values. It can improve the readability of your code when dealing with multiple conditions.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// Add more cases as needed
default:
// Code to execute if no case matches
}
Example:
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday"; // This will execute
break;
default:
dayName = "Unknown";
}
console.log("Today is " + dayName);
Note: The break
statement prevents the execution from falling through to the next case. If you omit it, the code will continue to execute until it encounters a break
or the end of the switch
.
6. Nested Conditional Statements
You can nest conditional statements inside one another to check for additional conditions within an existing conditional statement.
Example:
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
if (age >= 65) {
console.log("You are a senior citizen.");
} else {
console.log("You are not a senior citizen.");
}
} else {
console.log("You are not an adult.");
}
7. Ternary Operator
The ternary operator is a shorthand way to write simple if...else
statements. It is useful for assigning values based on a condition in a concise manner.
Syntax:
condition ? valueIfTrue : valueIfFalse;
Example:
let age = 20;
let status = (age >= 18) ? "Adult" : "Minor"; // Assigns "Adult" if age >= 18, else "Minor"
console.log(status); // Outputs: "Adult"
8. Logical Operators in Conditions
You can use logical operators to combine multiple conditions in a single conditional statement:
- Logical AND (
&&
): Returns true if both operands are true. - Logical OR (
||
): Returns true if at least one operand is true. - Logical NOT (
!
): Reverses the boolean value of the operand.
Example:
let score = 80;
let attendance = 90;
if (score >= 75 && attendance >= 80) {
console.log("You qualify for the scholarship!"); // This will execute
}
if (score < 75 || attendance < 80) {
console.log("You do not qualify for the scholarship.");
}
9. Coding Exercise
Now it’s time to practice what you've learned! Create a JavaScript file named conditionalStatements.js
and implement the following exercise:
- Write a program that takes a number as input and outputs whether it is positive, negative, or zero using an
if...else
statement. - Extend the program to check if the number is even or odd if it is positive.
- Implement the same logic using a
switch
statement.
Example Solution:
let number = 4; // Change this number for testing
// Using if...else
if (number > 0) {
console.log(number + " is positive.");
if (number % 2 === 0) {
console.log(number + " is even.");
} else {
console.log(number + " is odd.");
}
} else if (number < 0) {
console.log(number + " is negative.");
} else {
console.log("The number is zero.");
}
// Using switch (only for the sign)
switch (true) {
case (number > 0):
console.log(number + " is positive.");
console.log(number % 2 === 0 ? number + " is even." : number + " is odd.");
break;
case (number < 0):
console.log(number + " is negative.");
break;
default:
console.log("The number is zero.");
}
Conclusion
In this lesson, you learned about conditional statements in JavaScript, including if
, else
, else if
, and switch
. You also explored nested conditions, the ternary operator, and logical operators, all essential tools for controlling the flow of your code. Mastery of conditional statements is vital for building interactive and responsive applications.
In the next lesson, we will explore Loops, where you will learn how to execute blocks of code multiple times based on specific conditions.