Lesson · Chapter: Conditions+10 XP for reading
Making Decisions
Programs can make choices! Use if to run code only when something is true.
The if Statement
javascript
let age = 15;
if (age >= 12) {
console.log("You can ride the roller coaster!");
}
Output
Press Run to see the output.
The condition goes in parentheses ( ), and the code to run goes between curly braces { }. If the condition is true, the code inside the braces runs. If not, it's skipped.
Comparison Operators
| Operator | Meaning |
|---|---|
=== | Equal to |
!== | Not equal to |
< | Less than |
> | Greater than |
<= | Less than or equal |
>= | Greater than or equal |
Always use the triple === to compare — a single = stores a value instead of comparing!
if / else
Use else for when the condition is false:
javascript
let age = 8;
if (age >= 12) {
console.log("You can ride!");
} else {
console.log("Too young!");
}
Output
Press Run to see the output.
Output:
Too young!
if / else if / else
Use else if to check multiple conditions:
javascript
let score = 85;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("F");
}
Output
Press Run to see the output.
Output:
B
Boolean Logic
Combine conditions with && (and), || (or), and ! (not):
javascript
let age = 10;
let hasTicket = true;
if (age >= 8 && hasTicket) {
console.log("Enjoy the show!");
}
Output
Press Run to see the output.
Don't Forget the Parentheses and Braces!
The condition must be wrapped in parentheses, and the body goes in braces:
javascript
// Correct
if (age >= 12) {
console.log("Welcome!");
}
// Wrong — will cause an error!
if age >= 12
console.log("Welcome!");
Output
Press Run to see the output.