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

Tell us what’s happening:
Anyone care to tell me whats wrong here ?

Your code so far


function countOnline(usersObj) {
// change code below this line

for(let user in usersObj){
  let numOfCount = 0;
  if(usersObj[user].online === true){
    numOfCount++;
  } 
  return numOfCount;
}
// change code above this line
}

console.log(countOnline())

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 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-statement

your numOfCount variable will never be more than 1
the loop start, it is set the 0, then it may be or not be augmented by 1, new iteration, it is again set to 0… etc

plus, as you declared it with let inside the loop, it exists only inside the loop, the return statement is referencing a variable that was never declared in that scope

changed it a bit but still not working

function countOnline(usersObj) {
  // change code below this line
  for(let user in usersObj){
    if(usersObj[user].online === true){
      let numOfCount;
      numOfCount++;
    }
    return 0;
  }
  // change code above this line
}

now you are just returning 0

also, you can’t use ++ on a variable with value of undefined

numOfCount needs to be defined in he same scope/block in which you want to return it

also, if you want to make changes to it based on a loop, you can’t define it inside the loop as in that way there is just a different variable for each iteration

solved it!

  • i declared the numOfCount outside of the loop
  • used the loop to look over the keys of the object
  • if a key’s online value is true, increment it by 1 and return it with the return statement that i’ve placed outside of the loop

Thanks for your help

can you please post ur result i am trying for days i am not getting it please

If you have a question about a specific challenge as it relates to your written code for that challenge, just click the Ask for Help button located on the challenge. It will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.

Thank you.