[How come the code works / doesn't work]Iterate Through the Keys of an Object with a for...in Statement

Tell us what’s happening:

Your code so far


let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function countOnline(obj) {
  // change code below this line
  let numberOnline = 0;
  for (let user in obj){
    
    if (user.online){
      numberOnline ++;
          }
  }
  return numberOnline;
   
  
  // change code above this line
}

console.log(countOnline(users));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/-iterate-through-the-keys-of-an-object-with-a-for---in-statement

I have seen the code that can pass this task but I want to know why we still need to use
(obj[user].online) in the if statement? Since we have already loop through the users first.

Second, why do we have to use obj[user].online but obj.user.online doesn’t work?

Many thanks!

In both cases because user is a variable. Placing user inside brackets tells the parser to treat it as a variable and to use it’s value. When using dot notation, “user” is a literal string of characters.

1 Like

Thank you!! I understand it now and will check the link.