How to count object key iterations with a for...in statement

Hi everyone!

Nice to meet everyone. First time posting on here. I’m having troubles figuring out how to return a count total of whenever a user is “online”. My code looks like it detects that first “true” value and ends without iterating through the whole object. Looks like I might be overthinking things haha. Any help or guidance would be appreciated.

Thanks in advance!

  **Your code so far**

function countOnline(usersObj) {
// Only change code below this line
let count = 0;
for (let prop in usersObj) {
 while (usersObj[prop].online === true) {
   count++;  
   return count; 
 }  
}
}

console.log(countOnline({ Alan: { online: true }, Jeff: { online: true }, Sarah: { online: false } }))

  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36

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

Link to the challenge:

Hi @freddyk !

Welcome to the forum!

I don’t see the need for the extra while loop.

You can just use the for in.

You can have an if statement to take care of adding the users to the count.

You want to make sure your return statement is outside the for loop.

Hope that helps!

2 Likes

Thanks! Figured i’d use this great forum for some questions.

Seems like i’m running into the same issue when using an if statement. Is it the way i’m trying to access the key (online) value (true/false)?

I was able to pass with your code when I made those changes.

Can you post your updated code here?

When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

I forgot to add the return outside of the for loop! It works and makes sense on why it should be outside the loop. Thanks so much for clearing that up.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.