if...else
Statementif...else
in JavaScript?In JavaScript, the if...else
statement is used to perform conditional execution. This means that the program will decide which code to execute based on a condition. If the condition is true
, one block of code runs; if it's false
, another block (if provided) may run instead.
if
StatementThe if
statement executes a block of code only when the given condition is true
. If the condition is false
, the block is skipped.
let temperature = 30;
if (temperature > 25) {
console.log("It's a hot day!");
}
π In this case, since temperature
is greater than 25
, the message "It's a hot day!"
will be printed. If temperature
were 25
or lower, nothing would happen.
if...else
StatementThe if...else
statement provides an alternative block to execute when the condition is false
.
let temperature = 20;
if (temperature > 25) {
console.log("It's a hot day!");
} else {
console.log("It's a cool day.");
}
π Since temperature
is 20
, the condition is false
, so the else
block executes, displaying "It's a cool day."
if...else if...else
StatementWhen you have multiple conditions to check, you can use the else if
statement.
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 75) {
console.log("Grade: B");
} else if (score >= 50) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
π The program checks conditions from top to bottom. Since score = 85
, the second condition (score >= 75
) is true
, so "Grade: B"
is printed.
if
with Logical OperatorsJavaScript provides logical operators (&&
, ||
, !
) to combine multiple conditions.
let age = 20;
let hasID = true;
if (age >= 18 && hasID) {
console.log("You are allowed to enter.");
} else {
console.log("Entry denied.");
}
π Here, both conditions must be true
for access. If age
is below 18
or hasID
is false
, entry is denied.
if
StatementsYou can place if
statements inside other if
statements for more complex conditions.
let age = 25;
let hasTicket = true;
if (age >= 18) {
if (hasTicket) {
console.log("You can watch the movie.");
} else {
console.log("You need a ticket to enter.");
}
} else {
console.log("You are too young to watch the movie.");
}
π If age >= 18
, it checks for hasTicket
. If both conditions are true
, the user can watch the movie.
if
statement runs a block only if a condition is true.if...else
statement provides an alternative block when the condition is false.if...else if...else
statement checks multiple conditions in order.&&
, ||
, !
) help check multiple conditions together.if
statements allow more complex decision-making.