Question about a JavaScript exercise

I was doing the Iterate Through the Keys of an Object with a for…in Statement exercise in JavaScript and I tried submitted this as the solution but it didn’t work:

function countOnline(usersObj) {
  // Only change code below this line
  const onlinePeople = [];
  let count = onlinePeople.length;
  for (let user in usersObj) {
    if (usersObj[user].online === true) {
  return count
  // Only change code above this line

I already solved the exercise, but I’m wondering why my solution didn’t work. When I logged the onlinePeople array into the console, I got the users who were online, but the count variable still had a value of 0 even though I made it equal to the length of the array (which should have one user). Can someone tell me what’s wrong?

Where are you updating count to reflect the number of people who are online? Is there some other way you can get this count?

Why not just return onlinePeople.length instead?

count is not going to update unless you reevaluate the length and reassign it to the variable. Otherwise, it will just stay at 0

@lasjorg I actually did that already and it worked. I just wanted to know why the solution above didn’t work. I thought the count variable would automatically update once I used the “if” statement to push the users into the array.

count is a variable that is storing the length of the onlinePeople array at the time it is initialized. So unless you update the value of count at some point after that then it will still have the same value as when it was initialized. The array property length returns a number (the length of the array) but that’s it. It doesn’t link the variable holding that number to the array in any other way.

It’s generally a ‘bad thing’ if your code is updating random other values that you don’t explicitly tell it to update.

@bbsmooth That’s what I thought. I actually moved the initialization of the count variable to under the loop and “if” statement and it worked, but then I realized it would make more sense to just return the length of the onlinePeople array instead of putting it in a variable and then returning it. Thanks for the info

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