Basic Data Structures - Iterate Through the Keys of an Object with a for...in Statement

Tell us what’s happening:

Hello, I have run my code in Visual Studio Code, it is ok, the logic is correct IMHO. I test with //console.log(allUsers, users[allUsers]); and //console.log(count). Why does it not pass the tests?

BTW Is there anybody here in 2024?

Your code so far

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

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

console.log(countOnline(users));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0

Challenge Information:

Basic Data Structures - Iterate Through the Keys of an Object with a for…in Statement

This looks suspicious

You are not using the allUsers parameter correctly. The function is passed the users object when it is called.

Your loop should be someKey in allUsers not allUsers in users the key is a single value, i.e. the key in each of the allUsers objects.

You also need to be careful about your variable names, you are overwriting variables. The allUsers parameter starts out containing the users object, but then you make it a loop variable and overwrite it using the outer users object keys.


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

function countOnline(allUsers) {
  // users object pass to the function
  console.log(allUsers); // { Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }
  let count = 0;
  for (allUsers in users) {
    // now allUsers is the keys of the outer users object
    console.log(allUsers); // Alan, Jeff, Sarah
    if (users[allUsers].online === true) {
      count++;
    }
  }
  return count;
}
// users object pass to the function
console.log(countOnline(users));

Hello lasjorg,

I see the point, great explanation.