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 trialArikaturika Tumojenko
8,897 PointsCan someone please explain this syntax?
I have this code
var questions = [
{ question: "How many days are in a week?", answer: 7 },
{question: "How many weeks are in a month?", answer: 4},
{question: "How many months are in a year?", answer: 12 }
]
and this piece of code
for (var i = 0; i < questions.length; i += 1) {
var question = questions[i].question;
var answer = questions[i].answer;
My questions are:
- even if we changed the syntax, the objects are still seen as arrays? (therefore, we can access the array using index values - like here:
var question = questions[i].question;
- How come to access the value of "question" we use .question? Shouldn't we be using square brackets to get to a property's value?
1 Answer
Steven Parker
231,275 PointsYou can access the object value either way:
questions[1].question // you can use the DOT notation
questions[1]["question"] // or you can put the property name in brackets
Either way gives the same result.
Remember that questions is an array of objects.
Arikaturika Tumojenko
8,897 PointsArikaturika Tumojenko
8,897 PointsTherefore, each object has an index value. Now it makes sense why using the index notation. Thx a lot.