JavaScript Fundamentals · Conditions · Lesson 6 of 48
if, else if, and else
Concept
if, else if, and else
Conditions let a program make decisions by running different code depending on whether an expression is true or false.
JavaScript checks each condition top to bottom and runs only the first branch whose condition is true, skipping the rest.
By the end of this lesson
- Explain the core idea behind if, else if, and else.
- Predict output before running a change.
- Test one realistic and one unusual input.
- Use the result to make the next decision.
How to study this page
- 1. Read one concept.
- 2. Change the example.
- 3. Run, compare, and explain.
- 4. Complete the challenge below.
Syntax
if (condition) {
// code if true
} else if (anotherCondition) {
// code if that's true
} else {
// code otherwise
}ExampleRunnable
let score = 85;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else {
console.log("C");
}Try it Yourself »The ternary operator: a compact if/else
let age = 20;
let type = age >= 18 ? "adult" : "minor";
console.log(type);Note: Ternaries are great for a simple either/or value, but nested ternaries get hard to read fast.
Self-check before continuing
Without looking at the example, describe what changes when you modify one input in if, else if, and else. Then reopen the editor and prove your explanation with a small test.
You are ready to continue when you can predict, test, and explain the result.
Your turn
Write an if/else chain that prints "Pass" for scores 60 and above, and "Fail" otherwise.
Loading editor…
Console