cyberwombat
cyberwombat

Reputation: 40104

for vs forEach issue

if for and forEach are both synchronous why does the forEach loop not work and always return false in this case? I keep thinkining it's too early in the morning and I have made a glaring error. Both cases say they found a match:

var items = [{
  Code: 'BLAH',
  ItemID: 'FOO'
}];

console.log(findItem('BLAH')); // FOO
console.log(findItem2('BLAH')); // false

function findItem(sku) {
  for(var i in items) {
    if(items[i].Code === sku) {
      console.log('Match found - for'):
      return items[i].ItemID;
    }
  }
  return false;
}

function findItem2(sku) {
  items.forEach(function(item) {
    if(item.Code === sku) {
      console.log('Match found - forEach'):
      return item.ItemID;
    }
  });
  return false;
}

Upvotes: 1

Views: 80

Answers (1)

Pointy
Pointy

Reputation: 413757

The return inside the callback you pass to .forEach() just terminates that function call, not the "findItem2" call. In other words, the .forEach() mechanism itself has called the function you've passed it, and your return statement just returns from that; the overall process continues. Nothing ever pays attention to the value you return.

This is a case where the plain for loop is probably a little clearer. Some function frameworks might offer something like .forEach() specialized for the task of locating the first element in a list that satisfies a given condition.

Upvotes: 3

Related Questions