Tell us what’s happening:
I can"t figure out where i am mistaking. Is my variable ‘user’ directly refer to my user’s name when i declare it? (Despite the fact i didnt mention something like user = “Alan”, “Ryan” etc…
Your code so far
let usersOnline = 0;
for (let user in users) {
if (users.user.online == true) {
userOnline++
}
return userOnline
}
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
let usersOnline = 0;
for (let user in users) {
if (users.user.online == true) {
userOnline++
}
return userOnline
}
// change code above this line
}
console.log(countOnline(users));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0.
you are correct that you need to use bracket notation, but for online is not needed, you can access the property online with dot notation as that is the literal name of the property
you have removed a real important piece now
But im confused when you say that user is a string, because to me it is a variable, which i have declared in my for loop. Though, i agree that user is not a property from user. So i understand why it doesnt worck. Im still unable to understand how to navigate through users, to check every name…
you can’t do this because user has the value of a string, so it can’t have a property
you can’t do this because you are losing the variable
users is an object, it has many properties, at each iteration of the loop, user has the value of one of those property names. so you need to use bracket notation to access the nested objects which are the values of the properties of user
You are right, user is a variable, not a string, and at each iteration a string was assigned to the variable user (for example at the beginning of the first iteration the string “Alan” is assigned to to the variable user).
In your code the problem is that you are not using the variable user, instead you are using the string ‘user’:
users['user'].online == true
So to fix your code user must be a variable, not a string.
user is a variable
but if you try to do users.user your re trying to access the property named user, not named as the value that the user variable holds
you can’t use dot notation with variables because they are not evaluated to the value they hold
for a variable to be evaluated you need to use bracket notation