Lesson 2 · Unit 02
Conditionals
Flatten, tabulate and name your conditions
What you practise
- Nested
ifs flattened, a lookup table instead of a chain, boolean expressions simplified, a condition given a name
Try a question from this lesson
Pick one
An active, banned 16-year-old signs in. What comes back?
def access(user):
if user["active"]:
if user["age"] >= 18:
if not user["banned"]:
return "ok"
else:
return "banned"
else:
return "minor"
else:
return "inactive"function access(user) {
if (user.active) {
if (user.age >= 18) {
if (!user.banned) {
return "ok";
} else {
return "banned";
}
} else {
return "minor";
}
} else {
return "inactive";
}
}function access(user: User): string {
if (user.active) {
if (user.age >= 18) {
if (!user.banned) {
return "ok";
} else {
return "banned";
}
} else {
return "minor";
}
} else {
return "inactive";
}
}Hint
Go inward one level at a time, and stop at the first test that fails.
Correct answer
minor
Why
Active, so the first test passes. Under 18, so the second fails and its far-away else answers. The ban is never looked at. To read one case you held three open conditions in your head: that is the cost of nesting.
TypeScript noteUser is declared elsewhere as { active: boolean; age: number; banned: boolean }. The : string return type makes the compiler check that every path returns a string.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Flatten with guards
Turn each failing case into a guard clause: test for it, return, and forget it. What is left needs no nesting.
The cases now read from top to bottom like a list. Every else has gone, because nothing follows a return.
def access(user):
if not user["active"]:
return "inactive"
if user["age"] < 18:
return "minor"
if user["banned"]:
return "banned"
return "ok"function access(user) {
if (!user.active) return "inactive";
if (user.age < 18) return "minor";
if (user.banned) return "banned";
return "ok";
}function access(user: User): string {
if (!user.active) return "inactive";
if (user.age < 18) return "minor";
if (user.banned) return "banned";
return "ok";
}9 more exercises in the app
- 2× fill the blanks
- 2× type the answer
- 1× true or false
- 3× multiple choice
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.