Nested if Statements
Learn Nested if Statements
Nesting lets one condition be evaluated only after an outer condition succeeds.
In this lesson, you will study the rule, run a complete TypeScript example, explain its output, and test a small change.
What you’ll learn
- Explain the main rule behind nested if statements.
- Predict the result of the complete runnable TypeScript example.
- Recognize one common mistake and correct it.
Understand the concept
A nested if is useful when a second check only makes sense under a first requirement—for example, verifying a ticket after age eligibility. Deep nesting can make code difficult to read; combine independent booleans or use early returns in later lessons where appropriate.
See the concept visually
Use the diagram to locate the checks, values or branches involved in the example.
Run a complete TypeScript example
Save this code as main.ts or paste it into the TypeScript Playground. The example uses fixed values so it runs without prompting for input.
TypeScript code
const age: number = 22;
const ticket: boolean = true;
if (age >= 18) {
if (ticket) {
console.log("Enter");
} else {
console.log("Ticket required");
}
} else {
console.log("Age requirement not met");
}Verified output
EnterHow to run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. When using a project configuration, run the matching project build instead.
Trace the execution
The outer age check passes. Only then does the inner ticket condition execute. With ticket true the program prints Enter.
Predict the output before you run the sample. Compare each line with the source expression that produced it, and distinguish the type checker’s work from what happens in JavaScript at runtime.
Common mistakes and how to avoid them
An else is associated with the nearest eligible unmatched if. Use braces and indentation to make nesting readable.
Debugging habit: when a change is rejected, read the exact compiler diagnostic and inspect the operand types. When it compiles but behaves unexpectedly, follow the values through the JavaScript expressions.
Practice it yourself
Set age to 16 while leaving ticket true. Explain why the ticket condition is not evaluated.
Challenge: write down your prediction first, run the changed source, and explain any difference. Return to the verified version before continuing.
Check your understanding
Review the key idea
Nested if Statements: A nested if is useful when a second check only makes sense under a first requirement—for example, verifying a ticket after age eligibility.
The inner block is reached only when execution enters its enclosing branch.
Before continuing, be able to explain what is checked before execution and what actually changes at runtime in the example above.
Reaching the recap and completing the quizzes are separate milestones.