Hello! Can someone help me understand wwhy this loop is returning “undefined”. also, oonce arr has been looped through w/o any instance of “October”, I’d like to return “Have a great day”
function holidays(arr) {
// Do not use a variable to store your result
// ADD CODE HERE
for (let i = 0; i < arr.length; i++) {
if (arr[i] != "October") {
i++
} else if (arr[i] === "October") {
return "Happy Halloween"
}
}
}
// Uncomment these to check your work!
const months = ["April", "May", "June", "October"];
const animals = ["Cats", "Dogs", "Pigs"];
console.log(holidays(months)); // should return: "Happy Halloween"
console.log(holidays(animals)); // should return: "Have a great day!"
The for loop is only returning “Happy Halloween” if arr[i] === "October". If that doesn’t happen then the function just ends. And do you know what value gets returned automatically if a function doesn’t explicitly return a value?
shouldnt it at least return “Happy Halloweem” for the first array?
here is the update
function holidays(arr) {
// Do not use a variable to store your result
// ADD CODE HERE
for (let i = 0; i < arr.length; i++) {
if (arr[i] != "October") {
i++
} else if (arr[i] === "October") {
return "Happy Halloween"
}
else {return "Have a great day!"}
}
}
// Uncomment these to check your work!
const months = ["April", "May", "June", "October"];
const animals = ["Cats", "Dogs", "Pigs"];
console.log(holidays(months)); // should return: "Happy Halloween"
console.log(holidays(animals)); // should return: "Have a great day!"
So you are doing some extra incrementing that you don’t need. In your first if statement you are incrementing i if the value doesn’t equal “October”. But you have to remember that the for loop is also incrementing i every time through the loop. So when the value doesn’t equal “October” then you are incrementing i twice. Do you see how that will cause you to skip some strings in the array?