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!
This happens because you are returning from callback function of forEach and not from insideArray()
so in the end insideArray()
will always return false except in the case you match the last element in the array. you can fix the code by initializing value with false and removing else condition like this:
function insideArray (array, word) {
var value = "false";
array.forEach(function(each) {
if(each === word) {
value = "true";
}
});
return value;
}
Also note that you can write more simple code for this by using indexOf
:
function insideArray (array, word) {
return array.indexOf(word) >= 0 ? "true" : "false";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With