SOS Anybody see the mistake in this code? Basic Data Structures - Iterate Through the Keys of an Object with a for...in Statement

Tell us what’s happening:
Describe your issue in detail here.

Your code so far

const users = {
  Alan: {
    online: false
  },
  Jeff: {
    online: true
  },
  Sarah: {
    online: false
  }
}

function countOnline(allUsers) {
  // Only change code below this line
let count = 0;
for(let allUsers in users){
if ( users[allUsers].online === true){
return count+= 1
} else {
  return count = 0
}
}
  // Only change code above this line
}

console.log(countOnline(users));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5.1 Safari/605.1.15

Challenge: Basic Data Structures - Iterate Through the Keys of an Object with a for…in Statement

Link to the challenge:

It’s more helpful if you can use this to describe your issue, rather than creating an overly verbose topic title.

You’re not too far from getting this but your code needs a few tweaks.

Firstly, allUsers is the object which is passed to the function and users are the individual key/value pairs within allUsers. So, let allUsers in users and users[allUsers] are back-to-front.

Secondly, if you’re iterating an object and you have a return statement, you break out of the whole function immediately, before finishing the iteration. If you want to fully iterate the object, you should instead increment the count variable without returning it. (You also don’t need the else statement here as it’s redundant).

Finally, once you’ve iterated the object and counted the number of online users, you can then return the value of count at the end of the function.

Line with problem:

  for(let allUsers in users){
    if ( users[allUsers].online === true){
      return count+= 1
      return count = 0

Line missing:

return count;

Hey igorgetmeabrain!
Thanks a lot for the help I knew I was close, but I couldn’t figure out why.
It seems there is always something small I miss. Hopefully time and practice will correct this.

Thanks again for the help.

Hey WongYC-66,

Thanks a lot for taking the time to help! This challenge was a little tricky.
你好,WongYC-66,

非常感谢您抽出时间来提供帮助!这个挑战有点棘手。

1 Like