freeCodeCamp Challenge Guide: Iterate Through the Keys of an Object with a for...in Statement

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


Problem Explanation

  • Note: dot-notation will cause errors in this challenge.
  • [square-bracket] notation must be used to call a variable property name.
  • The following code will not work.

Hints

Hint 1:

for (let user in obj) {
  if (obj.user.online === true) {
    //code
  }
}

Hint 2

  • Example 2 demonstrates how using [square-bracket] notation the code will be executed.
for (let user in obj) {
  if (obj[user].online === true) {
    //code
  }
}

Solutions

Solution 1 (Click to Show/Hide)
function countOnline(usersObj) {
  // Only change code below this line
  let result = 0;
  for (let user in usersObj) {
    if (usersObj[user].online === true) {
      result++;
    }
  }
  return result;
  // Only change code above this line
}
38 Likes