Why does my for loop return the correct answer, but my forEach does not?

Viewed 100

this is my first question on SO. I have an assignment where I'm supposed to create a function that has two parameters--the first being an array of strings, and the second being a string to possibly match in the array.

I have two variations of the function: one uses a "for" loop, the other uses the .forEach() method. The for loop accurately returns "true"/"false" depending on whether or not the second parameter exists within the array. The forEach always returns "false".

Can someone explain why? Code below:

.forEach() version:

function insideArray (array, word) {
  var value;
  array.forEach(function(each) {
    if(each === word) {
      value = "true";
      return value;
    }
    else {
      value = "false";
    }
  });
  return value;
}

for loop version:

function insideArray (array, word) {
  var value;
  for(var i = 0; i < array.length; i++) {
    if(array[i] === word) {
      value = "true";
      return value;
    }
    else {
      value = "false";
    }
  }
  return value;
}

A sample array:

var heroArray = [ "spiderman", "wolverine", "batman", "greenArrow", "boosterGold" ];

Testing .forEach():

insideArray(heroArray, "spiderman");
"false"

Testing for loop:

insideArray(heroArray, "spiderman");
"true"

Thanks for any help in advance!

3 Answers
Related