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 JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2 Solution

E P
E P
2,215 Points

I don't get the dot notation

Here is what I have:

var students = [
  {name: "Jack", track: "web", achievements: 5, points: 8283},
  {name: "Lorry", track: "cat", achievements: 1, points: 140},
  {name: "Peter", track: "finance", achievements: 10, points: 9282},
  {name: "Jane", track: "design", achievements: 62, points: 9092823},
  {name: "Nick", track: "construction", achievements: 20, points: 3832}
];
var output = ""
for (var i=0; i<students.length; i++) {
  output += "<p>";
  for (var key in students[i]) {
    output += key+": "+students[i][key];
    output += "<br/>"; 
  }
  output += "</p>"
}
  document.getElementById('output').innerHTML = output;

So I am able to get my value of its key using students[i][key] but I don't understand why I can't use students[i].[key] as this seems to work: students[i].name.

I'm getting confused because I thought arrayname[indexvalue][indexvalue] was only used for 2 dimensional arrays.

3 Answers

Hi Lisa,

That's a great question. Here's a stackoverflow post explaining the difference between bracket and dot notation.

Edit: I spent a while trying to find a way of explaining this in my own words but felt the article was better. If it still doesn't make sense, please let me know and I'll do my best to explain this.

E P
E P
2,215 Points

Thank you Robert :) So I have to use bracket notation because property name is contained in a variable which is [key] in my situation. Did I get that correctly?

Yep, that's exactly right. The only time you can use dot notation is when you're using the actual property name or calling a function. In all other cases use bracket notation.

E P
E P
2,215 Points

Great. Thank you Robert for taking the time to answer my question!