Iterate with a for in loop

Tell us what’s happening:
I’m struggling with this one. What I have down should work, but it just keeps getting rejected. What am I missing?

Your code so far


function countOnline(usersObj) {
// Only change code below this line
let i = 0;
for ( let user in usersObj){
  if (usersObj[user].online === true){
    i++;
  }
  return i;
}
// Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36.

Challenge: Iterate Through the Keys of an Object with a for…in Statement

Link to the challenge:

you are always returning or 0 or 1, look at where you put your return statement

1 Like

Got it. So the return statement has to be outside the for in loop or it just resets. Thank you.

no, it doesn’t reset. The return statement stops the function and return a value. The loop was executed only for the first value of user and it didn’t reach any other value of user

Ok. So it doesn’t keep iterating if return is inside the loop, it just gives the first value of i.

it gives whatever the value of i is when the return statement is executed

This is slightly tangential, but the === true in the if statement is redundant. Since we know the online properties will be a boolean, simply writing it this way is all that’s necessary:

if (usersObj[user].online) {
1 Like