Create Multi-Condition if...else if...else Statements
In this step, you'll learn how to use multiple conditions with if...else if...else
statements in JavaScript to handle more complex decision-making scenarios.
Open the WebIDE and create a new file named multi-condition.js
in the ~/project
directory:
// Create a grade classification example
let score = 85;
if (score >= 90) {
console.log("Excellent! You got an A grade.");
} else if (score >= 80) {
console.log("Great job! You got a B grade.");
} else if (score >= 70) {
console.log("Good work! You got a C grade.");
} else if (score >= 60) {
console.log("You passed. You got a D grade.");
} else {
console.log("Sorry, you failed the exam.");
}
In this example, the if...else if...else
statement checks multiple conditions in sequence. The first condition that evaluates to true will have its code block executed, and the remaining conditions will be skipped.
Let's run the script to see the output:
node ~/project/multi-condition.js
Example output:
Great job! You got a B grade.
Now, let's modify the score to see how different conditions work:
// Try different score scenarios
let score = 55;
if (score >= 90) {
console.log("Excellent! You got an A grade.");
} else if (score >= 80) {
console.log("Great job! You got a B grade.");
} else if (score >= 70) {
console.log("Good work! You got a C grade.");
} else if (score >= 60) {
console.log("You passed. You got a D grade.");
} else {
console.log("Sorry, you failed the exam.");
}
When you run this script, you'll see a different output:
Example output:
Sorry, you failed the exam.
Let's create another example to demonstrate multi-condition logic with a different scenario:
// Weather condition example
let temperature = 25;
if (temperature > 30) {
console.log("It's very hot outside.");
} else if (temperature > 20) {
console.log("The weather is warm and pleasant.");
} else if (temperature > 10) {
console.log("It's a bit cool today.");
} else {
console.log("It's cold outside.");
}
This example shows how if...else if...else
can be used to handle multiple conditions with different outcomes.