In this video, you followed a visitor’s age through the day-trip ticket desk’s rules and saw how JavaScript picks exactly one path. Here are the key points:
- An
elseblock comes right after anifblock. It has no condition of its own. With just anifand anelse, theelseblock runs whenever theifcondition is false, so exactly one of the two blocks runs. In a chain withelse if, it runs only when every condition above it is false. - Between the
ifand theelse, eachelse ifadds another check: a condition in parentheses and a block in braces. - JavaScript checks the conditions from top to bottom. It runs the first branch whose condition is true and skips the rest of the chain without checking them.
- When two conditions are true for the same value, the one higher up wins. An age of 3 is under 5 and under 16, so the visitor gets free entry.
- If no condition is true, the
elseblock runs. - A line after the chain runs whichever branch ran, like any line after an
ifblock.
The desk’s rule table:
| Age | Ticket |
|---|---|
| Under 5 | Free entry |
| 5 to 15 | Child ticket |
| 65 and over | Senior ticket |
| Everyone else | Adult ticket |
Here’s the final script from the video:
ticket.js
const age = 30;
if (age < 5) {
console.log("Free entry");
} else if (age < 16) {
console.log("Child ticket");
} else if (age >= 65) {
console.log("Senior ticket");
} else {
console.log("Adult ticket");
}
console.log("Enjoy the trip");
$ node ticket.js
Adult ticket
Enjoy the trip
The video changed the age and ran the script again each time. These are the results it showed:
age |
First true condition | Output |
|---|---|---|
30 |
none, so the else block runs |
Adult ticket, then Enjoy the trip |
70 |
age >= 65 |
Senior ticket, then Enjoy the trip |
3 |
age < 5 |
Free entry, then Enjoy the trip |
5 |
age < 16 |
Child ticket, then Enjoy the trip |
Next, in Separate ifs, else if, or a Nested if?, you’ll compare this chain with the other shapes a decision can take.