In the last lesson, you watched the ticket desk give every visitor exactly one ticket. An if with else if and else checks its conditions from the top, runs the first branch whose condition is true, and skips the rest.
But a chain isn’t the only shape a decision can take: sometimes several things can be true at once, and sometimes one question only matters after another is answered. In this lesson, you’ll write chains yourself, then learn to choose between separate if statements, an else if chain, and a nested if, based on what the rule says. You’ll finish with a what-to-pack adviser that uses all three.
Write the Ticket Chain Yourself
Here’s the desk’s rule table from the video:
- Under 5: Free entry
- 5 to 15: Child ticket
- 65 and over: Senior ticket
- Everyone else: Adult ticket
This time, you’ll store the ticket in a variable and print it once after the chain, as with the battery tip in tip.js. Declaring it before the braces keeps it available after the chain.
In your course folder, create ticket.js and type in this script:
ticket.js
const age = 30;
let ticket = "";
if (age < 5) {
ticket = "Free entry";
} else if (age < 16) {
ticket = "Child ticket";
} else if (age >= 65) {
ticket = "Senior ticket";
} else {
ticket = "Adult ticket";
}
console.log(ticket);
The empty string "" is only a placeholder: because the chain ends with an else, one branch always runs and replaces it. Save the file and run it:
$ node ticket.js
Adult ticket
All three conditions are false for 30, so the else branch sets the ticket. Predict the ticket for 3, 5, 15, 16, and 65, then run each to check.
Keep the curly braces even on one-line branches, so a line you add later can’t land outside the branch.
Put Overlapping Conditions in the Right Order
An age of 3 makes both age < 5 and age < 16 true, so these two conditions overlap. Since the first true branch wins, their order decides the answer.
To see this, swap the first two branches and set the age to 3:
ticket.js
const age = 3;
let ticket = "";
if (age < 16) {
ticket = "Child ticket";
} else if (age < 5) {
ticket = "Free entry";
} else if (age >= 65) {
ticket = "Senior ticket";
} else {
ticket = "Adult ticket";
}
console.log(ticket);
Predict which condition JavaScript reaches first and whether it’s true, then run it: