Code Challenge: Pets
From Bold Idea Knowledgebase
Solving the "Pets" code challenge demonstrates a students' understanding of **boolean expressions**, **logical operators**, and **if-statements**.
Requirements
When running the program, it should do the following:
- After entering “dog” or “cat”, it should say the correct sound for that animal
- If you enter an age of 1 or 0, it should say “Just a pup” or “Just a kitten”, depending on the animal
- If you enter an age between 2 or 7 (including those numbers), it should say, “Your pet is still young”
- If you enter an age of 8, it should say “Your pet is elderly.”
The student should test their program several times, for example:
- enter "dog", then "1"
- enter "cat", then "1"
- enter "dog", then "4"
- enter "cat", then "7"
Solution
-
Fix the conditional in the first if-statement on line 7. It should say
if (animal === "dog")
. -
Fix the conditional in the second if-statement on line 11. It should say
if (animal === "cat")
. -
Fix the conditional in the 3rd if-statement on line 17. It should say
if (age < 2 && animal === "dog")
. -
Change the logical operator on the 4th if-statement on line 21 to
&&
. -
Fix the conditional in the 5th if-statement to check if age is greater than 2
and
less than 8. It should say
if (age > 2 && age < 8)
.
Example Solution
let animal = prompt("Enter your favorite pet (dog or cat)");
if (animal === "dog") {
alert("Arf!");
}
if (animal === "cat") {
alert("Meow!");
}
let age = Number(prompt("Enter the age of your pet:"));
if (age < 2 && animal === "dog") {
alert("Just a pup!");
}
if (age < 2 && animal === "cat") {
alert("Just a kitten!");
}
if (age > 2 && age < 8) {
alert("Your pet is still young.");
}
if (age >= 8) {
alert("Your pet is elderly.");
}