Help please Iterate Through the Keys of an Object with a for...in Statement

Help please Iterate Through the Keys of an Object with a for...in Statement
0

#1

Tell us what’s happening:
I am not sure why my code is not working

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 useNum = 0;
for (let user in obj){
  if (obj[user].online === true){
    useNum ++;
  }
  return useNum;
}
  // change code above this line
}

console.log(countOnline(users));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 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


#2

Look at where your return statement is. Your function is no longer executing after the first user because the return statement is in the for in loop. The return statement needs to be outside of the loop.


#3

OMG thank you so much! I don’t know why I didn’t even catch that. This has been driving me crazy.


#4

You’re welcome! :slight_smile: I’m not sure what editor you use, but if you use VS Code, I find the Bracket Pair Colorizer extension helps me when stuff like that happens. I can see right away that the return statement is not by the color bracket it should be (just how my brain works) and recognize the error faster than I would without it.