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 trialE P
2,215 PointsI 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
Robert Richey
Courses Plus Student 16,352 PointsHi 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
2,215 PointsThank 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?
Robert Richey
Courses Plus Student 16,352 PointsYep, 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
2,215 PointsGreat. Thank you Robert for taking the time to answer my question!