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

So basically I’m not understanding why the first block of code works but the second doesn’t?

for (let user in usersObj) {
if ((usersObj[user].online === true)){
userOnline++;
}
}

for (let user in usersObj) {
if ((usersObj[user][online] === true)){
userOnline++;
}
}

I had assumed that bracket notation works in all cases, but I guess in this case we need to use both bracket and period?

What is the reason for this?

Thanks.

If you are using bracket notation to refer to a property name directly (i.e. not through a variable), always wrap the property name in quotes so that JS can identify it as a string and look for the property name in the object accordingly. In other words, do:

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

If you just have [online], JS will think that online is a variable and try to get its stored value, which will of course result in error.

5 Likes

You are right gaac510. In a part of JS Basic they teach us to use the notation by periods and brackets, there it shows us that sometimes inside the brackets it is necessary to use quotation marks, generally when there are two words inside. I recommend that you play with those possibilities until it works.

1 Like

I see, thanks! Makes sense now.

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