In JavaScript, an if-else
statement is used to execute a block of code based on a condition. If the condition evaluates to true
, the code inside the if
block will run; otherwise, the code inside the else
block will run.
Syntax:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Example:
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
Explanation:
- If the variable
age
is greater than or equal to 18, the message"You are an adult."
will be logged to the console. - Otherwise, the message
"You are a minor."
will be logged.
Optional else if
:
You can chain multiple conditions using else if
.
let age = 25;
if (age < 13) {
console.log("You are a child.");
} else if (age >= 13 && age < 18) {
console.log("You are a teenager.");
} else if (age >= 18 && age < 60) {
console.log("You are an adult.");
} else {
console.log("You are a senior.");
}
In this example:
- If
age
is less than 13, it prints"You are a child."
- If
age
is between 13 and 17, it prints"You are a teenager."
- If
age
is between 18 and 59, it prints"You are an adult."
- Otherwise, it prints
"You are a senior."