Nested If - Else
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 26 of 77.
We can nest if-else if-else statements within each other. This allows us to create hierarchical decision-making structures.
For example:
let result;
if (age > 18) {
if (has_license) {
result = "You can drive";
} else {
result = "Get a license first";
}
} else {
result = "Too young to drive";
}It can be infinite nested:
if (condition1) {
// if condition1 is true
if (condition2) {
// if condition1 and condition2 are true
if (condition3) {
// if condition1, condition2 and condition3 are true
...
}
}
}Challenge
Create a program that checks if someone can enter a swimming pool.
Rules:
- Must be at least 10 years old
- If they are under 13, they must have an adult with them
Print exactly these messages:
- If too young:
Sorry, you are too young - If under 13 and no adult:
Sorry, you need an adult with you - If under 13 with adult:
You can enter with adult supervision! - If 13 or older:
You can enter by yourself!
Cheat sheet
You can nest if / else statements to make step-by-step (hierarchical) decisions:
let result;
if (age > 18) {
if (has_license) {
result = "You can drive";
} else {
result = "Get a license first";
}
} else {
result = "Too young to drive";
}Nesting means putting one condition inside another:
if (condition1) {
if (condition2) {
if (condition3) {
// All conditions are true
}
}
}Use nesting when each check depends on the previous one being true.
Try it yourself
let age = parseInt(inp[0]); // Don't change this line
let has_adult = inp[1] === "true"; // Don't change this line
// Write your code belowThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False