I would like to know why one of my solutions regarding value return does work and the others doesn’t
I have tried using two different syntaxes in the challenge you can see below. Unfortunately, I do not know why the second syntax doesn’t work.
**Works**
function countOnline(usersObj) {
// Only change code below this line
let result = 0;
for (let user in usersObj) {
if (usersObj[user].online == true) {
result++;
}
}
return result
// Only change code above this line
}
**Doesn't work **
function countOnline(usersObj) {
// Only change code below this line
let result = 0;
for (let user in usersObj) {
if (usersObj[user][online] == true) {
result++;
}
}
return result
// 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/91.0.4472.114 Safari/537.36
Challenge: Iterate Through the Keys of an Object with a for…in Statement
In JS, object property names are strings. So in the first one you are accessing a property named online. But in the second one you are accessing a property whose value you are getting from a variable named online. So if you put the word “online” in quotes then you can access it in the second method.
You are correct here that “online” needs to be in quotes because it, as an object property name , is a string. And without quotes it is an undefined variable.
As a note, object properties are not always strings. They can also be numbers.
If the property is a string without spaces you can use dot notation or brackets, but if the property is a number or a string with spaces you must use brackets.
The reason user does not need quotes is because it is a variable assigned to a property that is a string.
That syntax, as written without quotes, means ‘get the property with the value stored in the variable online’.
From MDN,
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. Working with objects - JavaScript | MDN
so the first stamement seems like a reasonable paraphrase of that as well.
FWIW, I don’t think it’s particularly useful or friendly to edit your post to point fingers at other people…
I wasn’t trying to point fingers at anyone. I should have said “seems” and phrased what I wrote differently. It’s all about learning here for everyone and I wasn’t intending to be mean. I edited my post.