Conditional Statements (if, else if, else)
Conditional statements are essential in programming to make decisions and execute different code blocks based on specific conditions. In JavaScript, you can use if
, else if
, and else
statements to create conditional logic.
1. The if
Statement
The if
statement is used to execute a block of code if a condition is true. The basic syntax looks like this:
if (condition) {
// Code to execute if the condition is true
}
For example:
let age = 18;
if (age >= 18) {
console.log('You are an adult.');
}
If the condition in the if
statement is true, the code inside the block will execute.
2. The else
Statement
The else
statement is used in conjunction with if
to execute a different block of code when the condition is false. Here's how it works:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
For example:
let age = 15;
if (age >= 18) {
console.log('You are an adult.');
} else {
console.log('You are not yet an adult.');
}
In this example, if the age is less than 18, the code inside the else
block will run.
3. The else if
Statement
Sometimes, you need to check multiple conditions. You can use the else if
statement to evaluate these conditions in a sequence. Here's how it looks:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if no conditions are true
}
For example:
let temperature = 25;
if (temperature > 30) {
console.log('It's hot outside!');
} else if (temperature >= 20) {
console.log('The weather is pleasant.');
} else {
console.log('It's cold outside.');
}
In this example, the code will evaluate the conditions in order, and the first one that is true will execute. If none are true, the code inside the else
block will run.
4. Nesting Conditional Statements
You can nest conditional statements inside one another to create more complex decision-making logic. Here's an example:
let isSunny = true;
let temperature = 28;
if (isSunny) {
if (temperature > 30) {
console.log('It's very hot outside!');
} else {
console.log('The weather is warm.');
}
} else {
console.log('It's not sunny today.');
}
In this nested example, the code first checks if it's sunny, and if it is, it evaluates the temperature condition.
Conditional statements are crucial for controlling the flow of your program and making dynamic decisions based on different situations. They allow your code to react to changing data and user input.
In the next section, we'll explore loops and how they can help you repeat tasks in your JavaScript programs.