Why does this code not loop through the object correctly

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

  **Your code so far**

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

// Only change code above this line
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15

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

Link to the challenge:

Howdy!

Check carefully the if inside your function.

What user[“online”] actually is? What value are you accessing? Is that the right answer or you should double check that bit of code?

isn’t it accessing the part of the object that checks if the user is online or not?

Check the MDN for…in docs and look at the examples.

If you think of it as for (const property in object) it might also help.

Example
const movies = {
  AirPlane: {
    watched: true,
  },
  Spaceballs: {
    watched: true,
  },
  "Zack Snyder's Justice League": {
    watched: false,
    note: "tl;dw"
  },
};

console.log(movies['AirPlane']); // { watched: true }

for (const movie in movies) {
  console.log(movie); // AirPlane, Spaceballs, "Zack Snyder's Justice League
  console.log(movies[movie]); // { watched: true }, { watched: true }, { watched: false, note: "tl;dw" }
}

On a slightly separate note, why can I do this

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

and not this

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

user is a variable. Revisit this challenge.

1 Like

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