Is there a general way to access nested objects?

let userActivity = {
  id: 23894201352,
  date: 'January 1, 2017',
  data: {
    totalUsers: 51,
    online: 42
  }
};

Take this object for example. If I wanted to set the ‘online’ property, don’t I have the choice to use either dot notation or bracket notation?

I sometimes have to try the possibilities to get it to work. So how do we alternate between using these notations? Are there any rules?

In the early challenges and so does now it’s stated that we can use both anytime

For this challenge I typed this to pass:
userActivity.data.online = 45;

What about this?
userActivity[data].online = 45;

or

userActivity[data][online] = 45;

What are all the correct forms?

In your example both userActivity[data].online = 45; and userActivity[data][online] = 45; would fail. The first expects data to be a variable and the second expects both data and online to be variables. To make it work, you would have to do userActivity['data'].online = 45; or userActivity['data']['online'] = 45;.

In other words: when you are referencing the property by name (and that name does not contain spaces), use dot notation. When you are referencing the property using a variable or operation, use bracket notation.

1 Like