You can put an if statement inside another if statement. This is called nesting:
const hasTicket = true;
const age = 10;
if (hasTicket) {
if (age < 12) {
console.log("Welcome! Here's your kids' popcorn. 🍿");
} else {
console.log("Welcome! Enjoy the movie.");
}
} else {
console.log("Sorry, you need a ticket first.");
}
It prints
Welcome! Here's your kids' popcorn. 🍿
Nesting works, but be careful. When you nest too deeply, your code starts looking like a staircase going sideways, and it becomes really hard to follow. Often you can flatten things out using && and else if:
const hasTicket = true;
const age = 10;
if (!hasTicket) {
console.log("Sorry, you need a ticket first.");
} else if (age < 12) {
console.log("Welcome! Here's your kids' popcorn. 🍿");
} else {
console.log("Welcome! Enjoy the movie.");
}
It prints
Welcome! Here's your kids' popcorn. 🍿
Same result, much easier to read. A good rule of thumb: if you're nested more than two or three levels deep, there's probably a simpler way.