if...else Statement
Learn if...else Statement
An if...else statement selects exactly one of two mutually exclusive branches.
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 if...else statement.
- Predict the result of the complete runnable TypeScript example.
- Recognize one common mistake and correct it.
Understand the concept
When the if condition is truthy, its block runs; otherwise the else block runs. Both paths rejoin after the statement. It is suitable when every case needs a clear response, such as pass versus fail.
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 marks: number = 68;
if (marks >= 40) {
console.log("Pass");
} else {
console.log("Fail");
}
console.log("Result checked");Verified output
Pass
Result checkedHow 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
68 passes the comparison, so the first branch prints Pass. The else branch is skipped. The final line executes regardless of which branch ran.
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
Do not use two independent if statements when the outcomes must be mutually exclusive; the else expresses that relationship explicitly.
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
Try marks = 39, then 40. Check which branch runs at the boundary.
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
if...else Statement: When the if condition is truthy, its block runs; otherwise the else block runs.
One branch handles the truthy case and the other handles the false case.
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.