Need some help in understanding

Tell us what’s happening:

Hi,

Why doesn’t the following code work? Why do I have to declare the entire path i.e object, value, and property?

Why?:

if(usersObj[user].online == true)

instead of:

if(user.online == true)

The object and users are already defined going into the if condition right. Shouldn’t it evaluate based on those values?

Your code so far


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

Your browser information:

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

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

Link to the challenge:

With this you are dynamically checking for the key in the object - just like you would do if you want to set an object’s key based on a user input or a variable.

For example:

let userKey = 'your name';
let obj = {
[userKey]: 'input' // userKey will be set as 'your name' in the end.
}

With this, you are checking if user key is literally present in the object.

PS: you don’t need to equate it to true as the code will only run if it’s true. if (userObj[user]) is enough. You could negate it if you want the code to run if false

the second part of @samolex post is not the correct.
The issue with this:

is just that user is a string, not the object you want to check

1 Like

You are right though

Well, this would be tedious I guess then.

It returns the value of every key in the object quite easily with a simple command.

for (let user in usersObj){
return user;
}

But to get any other value, I have to type the entire path of where it can find the specific property.

for (let user in usersObj) {
return usersObj[user].online;
}

Thanks for the help @samolex and @ilenia.

it returns just the first key, as a return statement stops a function


there is also the for…of loop, you could take a look at that one
each loop works differently

Guess the for …of loop was missing in the course. Will look it up.

Thanks, @ilenia.

many many things are not included in the course, that’s why you should find a documentation webside to consult as needed