By the end of this lesson, learners will:
if
, else if
, and else
if
Statements?Sometimes, you only want to run a piece of code if a certain condition is true.
For example:
This is where the if
, else if
, and else
statements come into play.
if
Statementif (condition) {
// code to run if condition is true
}
let age = 18;
if (age >= 18) {
console.log("You can vote!");
}
In this example:
age >= 18
is the condition"You can vote!"
is only printed if the condition is trueelse
StatementThe else
block runs if the condition is false.
if (condition) {
// run if true
} else {
// run if false
}
let isRaining = false;
if (isRaining) {
console.log("Take an umbrella.");
} else {
console.log("Enjoy the sunshine!");
}
🧠 Only one of the blocks will run, never both.
else if
StatementUse else if
to check multiple conditions, one after the other.
if (condition1) {
// run if condition1 is true
} else if (condition2) {
// run if condition2 is true
} else {
// run if none are true
}
let score = 72;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
🧠 JavaScript checks each condition in order, top to bottom, and runs the first one that is true.
()
for the condition{}
to define the code blockif
statements, but keep it readablelet temperature = 15;
if (temperature > 25) {
console.log("Wear a t-shirt.");
} else if (temperature > 15) {
console.log("Wear a light jacket.");
} else {
console.log("Wear a coat.");
}
This shows how JavaScript can adapt based on real-world data.
Try this in your browser console:
let time = 20;
if (time < 12) {
console.log("Good morning");
} else if (time < 18) {
console.log("Good afternoon");
} else {
console.log("Good evening");
}
🧠 Output: "Good evening"
You can combine multiple conditions using:
Operator | Meaning | Example |
---|---|---|
&& | AND | age >= 18 && age < 30 |
` | ` | |
! | NOT (negation) | !isLoggedIn |
if
checks a condition — code runs only if it’s true
else
handles the opposite — runs when the if
condition is false
else if
allows for multiple possible outcomes