Boolean logic is like it’s own kind of weird math. Understanding how to get that weird math to do what you want is essential to writing conditions in JavaScript. These practice problems get progressively harder to help you build your understanding of Booleans. You may want to review some of the rules of Boolean Logic here.
#1
If we have two variables isSunny
and isRainy
, and this expression:
isSunny && isRainy || !isSunny
Without running the code, figure out what it will evaluate to if…
isSunny = true, isRainy = false
isSunny = true, isRainy = true
isSunny = false, isRainy = true
isSunny = false, isRainy = false
#2
Rafael is adopting a dog. Here are his requirements:
- He wants it to be potty trained
- He wants it to either like to snuggle or like to play fetch (both is great too)
- He doesn’t want it to shed
Here’s a dog Rafael is considering:
let dog = {
name: "Milo",
sheds: true,
size: "big",
pottyTrained: true,
likesSnuggles: true,
likesFetch: true
}
Write a boolean expression to check if Rafael should adopt Milo. It should evalutate to false for Milo.
Testing
To know if you’ve written a boolean expression that works, try it with different dogs, some that should be accepted, some that should not. Don’t just run it, walk through it by hand and plug in the values and simplify it like the computer does. That will build your understanding of boolean logic.
Here’s another dog you could test with. It should evaluate to true for Penny:
dog = {
name: "Penny",
sheds: false,
size: "small",
pottyTrained: true,
likesSnuggles: true,
likesFetch: false
}
Answer
#3
Amy wants a dog too, but she’s pickier. Here are her requirements:
- She doesn’t want enormous amounts of hair in her apartment. So she doesn’t want a big dog that sheds. She’s fine with a small dog that sheds.
- If the dog likes to snuggle, it needs to be potty trained. She’s fine with a dog that isn’t potty trained, as long as it doesn’t also like to snuggle.
- The dog has to like playing fetch.
Here’s one dog she’s considering:
let dog = {
name: "Floof",
sheds: true,
size: "small",
pottyTrained: true,
likesSnuggles: false,
likesFetch: true
}
Write a boolean expression to check if Amy should adopt Floof. It should evaluate to true for Floof.
Testing
Here’s some more dogs you could test with.
It should evaluate to false for Rusty:
dog = {
name: "Rusty",
sheds: false,
size: "big",
pottyTrained: false,
likesSnuggles: true,
likesFetch: true
}
It should evaluate to false for Chonky:
dog = {
name: "Chonky",
sheds: false,
size: "small",
pottyTrained: false,
likesSnuggles: false,
likesFetch:false
}
Answer
Conclusion
How’d you do? Can you come up with more dog requirements and write boolean expressions for them?