-1

I am trying to understand the fundamentals of some js concepts, specifically on why my function returns on defined value

accountName is just a simple string, like "facebook" the return value of accounts is just an array

Original Function

function getAccount(accountName) {
    var accounts = Storage.getItemSync('accounts');
    var matchedAccount
    for(account in accounts){
      if (account.name === accountName){
        matchedAccount =  accountName;
      }
    }

   return matchedAccount;
}

Working Version

function getAccount(accountName) {
    var accounts = Storage.getItemSync('accounts');
    var matchedAccount

    accounts.forEach(function(account) {
        if(account.name === accountName){
            matchedAccount = account
        }
    });
    return matchedAccount;

}

The original function returns Undefined, while the working version returns the correct results. Why is this happening? Arn't I iterating over my array all the same?

John
  • 488
  • 4
  • 19

1 Answers1

1

This is simple but still a good question. In Javascript forEach works on Arrays while (for x in y) work on Objects*

while for..in does work on Arrays, because it enumerates through object fields, not indexes.

see this answer: Why is using "for...in" with array iteration a bad idea?

MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Community
  • 1
  • 1
omarjmh
  • 13,632
  • 6
  • 34
  • 42
  • ah I got it. Make sense, my account.name is not a part of the enumerable property of the accounts array. I logged both account and account.name, one returns 0, the other returns undefined. Which makes senses from what I read in the docs and that link. for.. in is iterating my array indices! Thanks! – John Mar 20 '16 at 01:05