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 Mixing and Matching Arrays and Objects

I need help understanding these 2 lines of code. Also why we used dot notation and not brackets?

for ( var i = 0; i < questions.length; i += 1) { question = questions[i].question; // LINE 1 answer = questions[i].answer; // LINE 2 etc. rest of code

2 Answers

As for using dot notation instead of brackets, both are fine. You can use brackets if you understand those better. Many JS developers seem to prefer dot notation so they use it more often (easier to type I guess), but both would work here: questions[i]["question"].

Looking at it piece by piece:

for (var i = 0; i < questions.length; i += 1) {
}

This is a for loop that iterates through an array named "questions." It will repeat the code inside it as many times as there are items in the questions array (that's what length is doing). Basic info about for loops here.

question = questions[i].question;

i is the numeric index of the for loop, so for the first loop it's 0, for the next it's 1, etc. questions[i] is just picking a specific item in the questions array, so for the first loop it's questions[0], which is the first item in the array since array indexes start at 0. questions[i].question is getting the value assigned to the question key in that specific array item. So if it was:

var questions = [
  { question: "Knock knock", answer: "Who's there?" }
];

then questions[0].question would return "Knock knock". Then that value is assigned to the question variable by using equals: question = (whatever).

The exact same thing is done for that array item's answer on the next line.

Can you show me how can I use brackets to access the value?

question = questions[i]["question"];
answer = questions[i]["answer"];

Thank, I understood