Reputation: 35
This seems so simple but I just don't get it. Why when I pass b and c through the function below, and the if statement returns true, and I use a return statement, I get undefined?
function stockList(arr1, arr2){
arr1.forEach(function(elB){
for (var elC in arr2){
if (elB.charAt(0) === arr2[elC]){
return "hello"
}
}
})
}
b = ["ABAR 200", "CDXE 500", "BKWR 250", "BTSQ 890", "DRTY 600"]
c = ["A", "B"]
stockList(b,c)
I expect the result to be "hello" but I get undefined. I have a feeling I'm going to hit my head and go "doh" when I discover the problem. Thanks for any response.
Upvotes: 1
Views: 45
Reputation: 44107
forEach
doesn't return anything. Use two for
loops, and maybe add a catch-all return
at then end of the function too:
function stockList(arr1, arr2) {
for (var elB in arr1) {
for (var elC in arr2) {
if (arr1[elB].charAt(0) === arr2[elC]) {
return "hello"
}
}
}
return "goodbye";
}
b = ["ABAR 200", "CDXE 500", "BKWR 250", "BTSQ 890", "DRTY 600"]
c = ["A", "B"]
console.log(stockList(b, c));
Upvotes: 1
Reputation: 3997
You are returning hello from an inner function: the forEach. If you want to return hello from the main function, do not use a forEach, use a simple for loop.
Upvotes: 0