Working through some javascript array exercises to solidify my understanding. Came across an exercise that I'm able to solve easily using a for-loop, but not using the forEach() method. Why is happening, and how would I correct for this?
Here's the exercise question listed out, and my code using both methods below: "Write a function that takes an array of values and returns an boolean representing if the word "hello" exists in the array."
function hello_exists(array){
for(i = 0; i < array.length; i++){
if(array[i] === "hello"){
return true
}
}
}
var my_arr = ["some", "hello", "is", "cat"]
hello_exists(my_arr) // returns true as expected
function hello_exists(array){
array.forEach(function(val){
if(val === "hello") {
return true
}
})
}
var my_arr = ["some", "hello", "is", "cat"]
hello_exists(my_arr) // returns undefined. not sure why?