For...in statement challenge help

Tell us what’s happening:

why is my code not working

Your code so far


function countOnline(usersObj) {
// Only change code below this line
var c=0;
for(let user in usersObj)
{
if(user['online']==true)
{c+=1;}
}
return c;
// 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/83.0.4103.116 Safari/537.36.

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

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-the-keys-of-an-object-with-a-for---in-statementPreformatted text

Think about what this line does:

if(user['online']==true)

What is user and what is it in reference to?
Do you see a problem with user['online']?

for every iteration in the for loop user changes from one name(key) to another through which we can access the online property of different names in the object

Good. But let’s say that user is Sarah in your current iteration. What is Sarah.online without context? It’s nothing.
When you iterate through a for...in, in this case user, user is just a key string (Sarah for example). It’s not a reference to an object inside your {} statement following for...in. It seems redundant, but there’s no reference to usersObj.Sarah

if(user['online']==true) is not valid because you’re checking if Sarah.online is true.
What you want to check is if usersObj.Sarah.online is true.

1 Like