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

Tell us what’s happening:
I’m doing the for in loop and I tested my code in Codepen and the result counts 0,1,2,3 as intended when I directly use “users” as the object literal instead of the parameter “usersObj”.

Although the the fcc console only accepts usersObj[names].online

  **Your code so far**
const users = {
Alan: {
  online: false
},
Jeff: {
  online: true
},
Sarah: {
  online: false
}
}

function countOnline(usersObj) {
// Only change code below this line
let i = 0;
for (let names in users) {
if(users[names].online === true) {
  i++;
}
}
return i;
// 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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

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

Link to the challenge:

1 Like

yes, because your function should be reusable. if you use usersObj it’s reusable and can be used with different objects

Let’s say you want to run this code

const randomObj1 = {sam:{online:true}, max:{online:true}}
const randomObj2 = {sam:{online:false}, max:{online:true}}
countOnline(randomObj1)
countOnline(randomObj2)
countOnline(users) //(users is your object)

How do you make the function succeed at logging each online count ?

1 Like

Use argument for different objects.
Although I understand that the real world would only have one name per user that’s probably why I didn’t pay attention to the re-usability.

But I do understand the applicability of using the argument instead of the object name now.

Thankyou.

An important concept is the parameters here. If the object is always “users”, the function does not need a parameter in the definition.

To be precise:

function countOnline() {
//...
}

That would be equivalent. But it is not what we want/ We want an argument to reuse it, and also to isolate that functionality etc.

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