Accessing object property

Tell us what’s happening:

Hello, I’m wondering why accessing the object property this has to be done with dot usersObj[user].online and not square brackets usersObj[user][online], why is it like that, don’t they do the same thing?




**Your code so far**
      
```js

function countOnline(usersObj) {
// Only change code below this line

let answer = 0;
for (let user in usersObj){

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

    answer++;;
  }


  

}

return answer;

// Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0.

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

Link to the challenge:

You can access object using both syntax, as they are both valid since each property is associated with a string key value.

Or in practice:

let o = new Object();
o['with space'] = "I am a valid property";

// Object { "with space": "I am a valid property" }

For the above, would be impossible to access the with space key using the . notation

o.with space // Error
o['with space'] // "I am a valid property"

You can read more about Property Accessor on MDN.
Hope it helps :sparkles:

But the exercise said that this was wrong usersObj[user][online] but this usersObj[user].online was for some reason the correct answer, why is it like that?

Re read the comment above: the square notations requires a string to access it.
I doubt online is a string :slight_smile:
Maybe: usersObj[user]['online'] ?

1 Like

Oh, sorry, my bad! Thank you for the help!

Object keys in JS are strings* – you should read this:

{
  user: {
    online: true,
  },
}

as this:

{
  "user": {
    "online": true,
  },
}

So

  1. JS syntax: "this is a string" whereas thisIsAVariable. The quotation marks denote a string.
  2. Dot syntax for object access is for accessing a property by the literal name of the key, and keys are strings
  3. Bracket syntax is saying “evaluate what is in the bracket to a string before accessing the property”. usersObj[user] → usersObj["Alan"] → usersObj.Alan
usersObj[user].online
          ↑      ↑
      variable  string 
usersObj[user]["online"]
          ↑       ↑
      variable   string 
usersObj[user][online]
          ↑       ↑
      variable  variable

* edit: for future reference re. keys always being strings – this is not 100% true – they can be integers or Symbols (which are special type of unique value), but you don’t need to worry about that at the minute, assume they are always strings

1 Like

Thank you for the great explanation! This helped me understand this even better!