Nested Conditions
Control Structures · Complex game logic (e.g. power-up + collision + direction).
Nested Conditions
What it is
Nested conditions are if statements inside other if statements. They’re used when a check only makes sense after a previous check has passed — e.g. you can only ask ‘did the player land on top?’ if you’ve already confirmed ‘did the player collide at all?’.
Why it matters
Some logic genuinely can’t be flattened into a single compound expression. If condition B is only meaningful when condition A is true, nesting reflects that dependency clearly. A flat chain of && operators would conceal the structure.
How GateGame implements it
NPC interaction logic uses nested conditionals. The outer check verifies the iterated object is the right class (obj.class === Npc); the inner check confirms an interact method exists before calling it. This prevents undefined is not a function errors when an entity in the array doesn’t have an interact handler.
Code Example
// Nested: class check → method existence check → call
for (const obj of this.classes) {
if (obj.class === Npc) { // outer: is this an NPC?
if (obj.data.interact) { // inner: does it have interact()?
if (player.isNear(obj)) { // deeper: is player in range?
obj.data.interact();
}
}
}
}
Key Takeaway
Nest when each check depends on the previous one passing. Flatten when the conditions are independent.