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

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

#1

Tell us what’s happening:

Hey guys :slight_smile: My first post on here! I’ve been struggling to find a bug in this code. It keeps outputting 0, as if it’s not incrementing userNumber like I want it to. Could anyone please point out my mistake?

Thank you!

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
  
  for (let user in obj) {
    let userNumber = 0;
      if (obj[user]['online'] == true) {
        userNumber++;
      }
      return userNumber;
  }
  // 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

try this:
obj[user][“online”]
instead


#3

Your for loop only iterates through the first user object of users before returning the value of userNumber. Remember, once a return statement has been executed, the function exits immediately.


#4

Thank you! Solved :slight_smile: