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
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