Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

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;
console.log(entreeValue);

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
230,274 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"].