Iterating with for...in statements

Iterating with for...in statements
0

#1

**Tell us what’s happening:
I don’t know what the problem with my code is, I’ve rewritten it several times now.

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) {
    var num = 0;
    for (let i = 0; i < 5; i++) {
      if (user.online === true) {
        num++;
      }
    }
  }
  return num;
  // change code above this line
}

console.log(countOnline(users));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; 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

The num declaration should be outside the for-in loop. Otherwise it will reset to 0 every time.

You don’t need the inner for loop, since you’re only supposed to loop through the object’s properties (which is already being done by the for-in loop).

Finally, the user variable in the for-in loop will not hold an inner object, but rather the property name itself (e.g. "Alan", "Jeff", etc). You’ll have to refer to each inner object via bracket notation, like obj[user]


#3

for...in is a loop, it loops over the object. Even if you move that var num outside the for…in loop, by adding another loop inside the main loop, all you’re going to do is cause num to increase by 5 instead of 1 every time an online user is found


#4

Thank you guys, I used obj[user].online and removed the second loop. I also moved the num variable outside the for…in loop and I successfully completed the task.