Iterate Through the Keys of an Object with a for...in Statement spent an hour on this

Tell us what’s happening:

Your code so far


let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function countOnline(obj) {
  // change code below this line
  let count = 0
  for (let user in obj) {
    if (obj[user]['online']) {
     count += 1;
    };
  return count
  }
  // change code above this line
}

console.log(countOnline(users));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/-iterate-through-the-keys-of-an-object-with-a-for---in-statement

Your return count; line is inside the for loop, which means it breaks the loop in the first iteration.

2 Likes

yup. As @ghukahr has said, the return being inside that for(...) loop returns at the first attribute found. Simply move the return statement down one line, so that it becomes the last line of the function (well, next-to-last – just before the //change code above this line line).

1 Like

Thank you @snowmonkey and @ghukahr for the help!

Yep, just did this one. Bone crusher. LOL!