Hey there, I'm new to SO and seeking some guidance. I have a task where I need to create a function with two parameters - an array of strings and a string to potentially match within the array.
I've developed two versions of the function: one using a "for" loop and the other utilizing the .forEach() method. Surprisingly enough, the for loop version correctly returns "true" or "false" based on whether the second parameter matches an element in the array, while the forEach version only returns "false".
Any insights into why this might be happening? See code snippets 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;
}
Here's a sample array:
var heroArray = [ "spiderman", "wolverine", "batman", "greenArrow", "boosterGold" ];
Testing .forEach():
insideArray(heroArray, "spiderman");
"false"
Testing for loop:
insideArray(heroArray, "spiderman");
"true"
Appreciate any assistance you can provide!