If you move off the forEach() requirement - You can also use .includes()
which is a newer method of determining if a string exists in an array. -link - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
This is the way I would do it - but note that IE typically does not support it. But then no one likes IE anyway :)
Also note: When comparing strings and characters, includes() is case-sensitive.
ps - thanks to @vanowm for the skeleton of the solution that I modified to suit my approach :)
function droids(arr) {
return arr.includes("Droids")
? "Found Droids"
: "These are not the droids you're looking for.";
}
const starWars = ["Luke", "Finn", "Rey", "Kylo", "Droids"]
const thrones = ["Jon", "Danny", "Tyrion", "The Mountain", "Cersei"]
console.log(droids(starWars)) // should log: "Found Droids!"
console.log(droids(thrones)) //should log: "These are not the droids you're looking for."
If you absolutely have to use forEach - then its a simple comparison of each item in the array to the target string. Note that you only update the result string if the string matches - if you update on both the matched and non matched string - any non matches after a match will revert the restult to the not-matching text.
function droids(arr) {
let result = "These are not the droids you're looking for."
arr.forEach(function(arrItem){
if (arrItem === 'Droids') {
result = 'Found Droids'
}
})
return result
}
const starWars = ["Luke", "Finn", "Rey", "Kylo", "Droids"]
const thrones = ["Jon", "Danny", "Tyrion", "The Mountain", "Cersei"]
console.log(droids(starWars)) // should log: "Found Droids!"
console.log(droids(thrones)) //should log: "These are not the droids you're looking for."