Challenge 209: Accessing Nested Objects

In the main example to the left, how do you know which property gets brackets in the accessing line at the bottom? For example, why is “top drawer” enclosed by brackets and not “drawer”?

thanks,
Danny

If your property on an object is multiple words, you have to use bracket notation. Also, if you are dynamically accessing it via a string, you have to use this as well.

For example,

var myObject = { a1: '1', a2:'2' };

var i = 1;

console.log(myObject['a' + i]);
2 Likes

If a key includes one or more spaces, then you must use bracket notation. Otherwise, you are free to use either bracket or dot notation. In my experience, it’s far more common for programmers to not use spaces in their property names, so dot notation is what I see the most. Bracket notation is handy if you’ve gotten your data from a third party, like some web API or a database. In that case, you’re far more likely to see spaces in the object keys.

1 Like

thanks guys, I should have read the final instructions part of the challenge and would of figured that out.

1 Like

Bracket notation is typically used when the property name is stored in a variable. If a specific property is being called, the convention is to name it such that you can use dot notation.

1 Like