Why Brackets work but dot doesnt?

For the condition of the “if” statement, why does
(usersObj.user.online === true)
doesn’t work but
(usersObj[user].online === true)
does. I can’t understand why i can’t access the value of the ‘online’ key through dot notation.

Sorry if it’s a silly question.

  **Your code so far**

function countOnline(usersObj) {
// Only change code below this line
let isOnline = 0
for (let user in usersObj) {
  if (usersObj.user.online === true) {
    isOnline++;
  }
}
return isOnline
// 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/96.0.4664.93 Safari/537.36

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

Link to the challenge:

Precision and consistency is key in JavaScript.
Using the usersObj.user.online makes more sense to access the child components of the usersObj object.
Most probably JavaScript trying to tell you to be consistent!

Dot notation cn only be used with the exact literal name of a property. When you have a variable that holds the name of the property, you have to use bracket notation.

1 Like

Building on that…

If I have this:

const data = {
  maria: { age: 37 },
  bob: { age: 32 },
}

Then these:

data[user].age
data.user.age

mean two very different things. The first one is holding a user name in a variable. The second is assuming that there is a user named “user”.

The first one works like this:

const user = 'maria'
data[user].age // 37

The bracket notation tells JS that “user” is really a variable and to use the value stored in that variable. It is equivalent to this:

data.maria.age // 37

But using a variable makes it a lot more flexible.

2 Likes

Thank you very much. Crystal clear now.

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