-1

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?
  • Have you tried to use the same comparison in both methods? `array[i] = "hello"` is different than `val === "hello" ` – Fabio Aug 18 '15 at 21:16
  • 2
    possible duplicate of [Why does this forEach return undefined when using a return statement](http://stackoverflow.com/questions/7209794/why-does-this-foreach-return-undefined-when-using-a-return-statement) – JJJ Aug 18 '15 at 21:16

3 Answers3

4

Returning true in forEach does not actually return a value to the caller and has no effect.

The callback passed into forEach is designated to perform a set of operations in iteration(without returning anything)

Use a variable to return after the forEach has finished executing

function hello_exists(array){
  var exists = false;
  array.forEach(function(val){
    if(val == "hello"){
         exists = true;
    }
  });
  return exists;
}

As an alternative, you can use some()

function hello_exists(array){
  return array.some(function(val){
    return val == "hello";
  });
}

or filter() with checking the length on the results

function hello_exists(array){
  return array.filter(function(val){
    return val == "hello";
  }).length > 0;
}
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
1

Your second hello_exists function is not returning anything. It may look like it is because you have the 'return' in there, but that is in the forEach function.

In the second example, you need to return something for the hello_exists function. Something like this would work

function hello_exists(array){
  var isTrue = false
  array.forEach(function(val){
    if(val === "hello") {
      isTrue = true
    }
  })
  return isTrue
}
var my_arr = ["some", "hello", "is", "cat"]

hello_exists(my_arr) // true
mccalljt
  • 786
  • 3
  • 14
1

It can also help to understand what's happening if you imagine a simplified implementation of forEach:

function forEach(array, fn) {
    var i;
    for (i = 0; i < array.length; i++) {
        fn(arr[i]);  // forEach doesn't care about what the function returns
    }
}
pdenes
  • 782
  • 6
  • 9