Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Richard Verbraak
Richard Verbraak
7,739 Points

Accessing objects with . and []

I'm confused as to how you can access an objects property / key with the 2 different methods.

Example from FCC where I just changed the first key name for testing.

var testObj = {
  name: "hamburger",
  "my side": "veggies",
  "the drink": "water"

var entreeValue = testObj.name;

This logs hamburger for me which I get but why is it that I get undefined back when I use test.Obj[1]. Shouldn't this return hamburger which is indexed on 1?

I thought objects were similiar to arrays? Do they not have an index like an array? Or am I just confusing the 2 because I'm not sure when you would use an array over objects or vice-versa.

I'd appreciate it A LOT if someone could clear the differences up.

1 Answer

Steven Parker
Steven Parker
220,925 Points

Using the bracket notation for attribute access might look like indexing but it's a bit different. Instead of using a numeric index as with arrays, brackets for accessing attributes contain the name of the attribute as a string.

So the bracket equvalent of   testObj.name   would be   testObj["name"].