Iterate Through the Keys of an Object with a for...in Statement HELLPPP!

Tell us what’s happening:
I don’t think I am understanding how to use a for…in statement, could anyone explain it to me in their own words?

Your code so far

js

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
for (let online in users)
  // change code above this line
}

console.log(countOnline(users));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 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

in The for…in loop have this structure

for (let prop in obj) {
// do this for each prop
}

With prop being the key of a different property at every iteration

For example, an object like

let romanNums = {
   1: "I";
   5: "V";
   10: "X";
}

If you iterate over this object

for (let num in romanNums) {
   console.log(num)
}

In this case you would have printed in the console the keys of the properties "1", "5", "10"(always as strings!)
If you want to have the values of the properties you need to use a way to access it - bracket notation!

2 Likes