Nested Conditionals
Learn about nested conditionals
Nested Conditionals
What are nested conditionals?
Nested conditionals are if statements inside other if statements. They let you check conditions based on the results of previous conditions.
Benefits of nested conditionals?
- Handle complex decision trees
- Only check certain conditions when others are true
- Create multi-level game logic
- Reduce unnecessary checks
- Build hierarchical decision structures
const playerHealth = 50;
const hasWeapon = true;
const targetDistance = 5;
const weaponRange = 10;
if (playerHealth > 0) {
console.log("Player is alive");
if (hasWeapon) {
console.log("Player has a weapon");
if (targetDistance <= weaponRange) {
console.log("Target is in range!");
console.log("ATTACK!");
} else {
console.log("Target is too far away");
}
} else {
console.log("Player has no weapon");
}
} else {
console.log("Player is dead");
}
What does this code do?
- First
ifchecks if player is alive - Inside that, second
ifchecks if player has weapon - Inside that, third
ifchecks if target is in range - Each level only runs if all previous conditions were true
// Game state logic
const isPlaying = true;
const isPaused = false;
if (isPlaying) {
if (!isPaused) {
console.log("Game is running - update game objects");
} else {
console.log("Game is paused");
}
}
What does this code do?
- First checks if game is playing
- Then checks if game is NOT paused
- Only runs game update code if both conditions are true
- Shows practical game state management
- Prevents updates when game is paused or not running
Try It Yourself
%%js // CODE_RUNNER: nested-conditionals const level = 2; const health = 80; if (level > 1) { if (health > 50) { console.log(“Ready for boss”); } else { console.log(“Heal first”); } }