I need some help in this challenge, I would be super grateful if you give me a hand

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

const users = {
Alan: {
  online: false
},
Jeff: {
  online: true
},
Sarah: {
  online: false
}
}

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

console.log(countOnline(users));
  **Your browser information:**

User Agent is: Mozilla/5.0 (iPhone; CPU iPhone OS 15_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.3 Mobile/15E148 Safari/604.1

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

Link to the challenge:

HI @Mikael3211 !

Pay close attention to where you placed your return statement.
What your code is saying is if this if statement is false then return the result

You don’t want that.
You need to go through the entire object and once the loop is finished then you return the result.

Hope that makes sense!

Sorry, I’m still confused.

Manually walk through your code here
I also formatted your code too :grinning:


const users = {
  Alan: {
    online: false
  },
  Jeff: {
    online: true
  },
  Sarah: {
    online: false
  }
}

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

console.log(countOnline(users));

In your code we start going through the for loop.
We check this condition here

  if (usersObj[user].online === true)

The first user on the list is Alan correct?

 Alan: {
    online: false
  },

We can see that his status for online is false which means our if statement will not run.
So we move to this return here

return result;

return statements will exit the function and return a value.
Your code is returning 0 and not even getting to the rest of the users on the list.

You need to move your return outside of the loop because we need to check each user in the list to see if they are online.

Make sense?

I will try to do that challenge later because I’m tired and frustrated of spending days stuck at this difficult challenge. Anyway thanks for your time.

Taking breaks is good.
I will say that you are close to solving it.
Once you move the return result outside of the for loop then it will pass.
But is it also important to understand how your code is working too.

Maybe after some time away you will understand the flow of your code better.
If you have further questions down the line, just let us know :grinning:

Thank you very much my friend, Everything is clear now, I’ve passed the test :smiley:.

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