Help me with my for...in Statement

Tell us what’s happening:

I’ve been trying to get pass this topic, but i can’t get it right. I can’t Seem to figure out What wrong with my code, The For in loops through each Name, then my if statement checks if its online and ill add 1 to my count. and return that count

I would put a link to the topic but it wont let me
Basic Data Structures: Iterate Through the Keys of an Object with a for…in Statement

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
  }
};

console.log(users[1].online);
function countOnline(obj) {
  // change code below this line
  var count = 0;
  for(let user in users){
  if(obj[user].online == true){
    count = count +1;
  }   
 }
 return count;
}
  // 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/71.0.3578.98 Safari/537.36.

For in loop through each enumerable properties of an object.

So to make it simple:

when you write a for loop you increase an index and access the element of an iterable through that index.
With a for in you are iterating over each property.

In practice:

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

for(user in users) {
  console.log(user) // Alain Jeff Ryan
}

So you want to access:

 users[user]

Hope it helps :wink:|


EDIT: that said mind also that the data you are looping match:

for(let user in users) // loop over users data
/* and */
if(obj[user].online == true) // condition based over obj argument
1 Like

First of all I there’s an error here console.log(users[1].online);, notice that you don’t have an array of objects, instead you have an object with some nested objects in it as properties. Try logging this console.log(users[0]), this should output undefined because that’s not how you access object properties, but if you log the following console.log(users.Alan) you should get this {age: 27, online: false} which I suspect is the result you’d expect.

As for the for...in loop, I’d recommend reading the documentation here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Hint: the problem is here obj[user].online, why are you using the keyword obj?

1 Like

Thank you, I guess I was confused with accessing objects and arrays. Once I changed that line, the solution worked.