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

Kishan P
Kishan P
9,921 Points

I am confuse with the brackets?

  var questions = [
    { 
    question: 'How many states are in the United States?', 
    answer: 50
    },
    {
    question:'How many continents are there?', 
    answer: 7
    },
    {
    question: 'How many legs does an insect have?', 
    answer :6
    }
  ];
  var correctAnswers = 0;
  var question;
  var answer;
  var response;

  function print(message) {
    document.write(message);
  }

  for (var i = 0; i < questions.length; i += 1) {
    question = questions[i].question;
    answer = questions[i].answer;
    response = prompt(question);
    response = parseInt(response);
    if (response === answer) {
      correctAnswers += 1;
    } 
  }

  html = "You got " + correctAnswers + " question(s) right."
  print(html);

Why we using the bracket [] and not the {} for array of objects. And i don't understand this part

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

1 Answer

Eric M
Eric M
11,546 Points

Hi Kishan,

The square brackets and curley braces mean different things. Squre brackets in JavaScript are used for array indexing. Curley braces are used for code blocks and JSON key/value pair blocks.

Note that questions is an array of objects. There are multiple key value pair JSON objects within the questions array. We have to find the index, then from the index we can access the value corresponding to the key by referencing the key with dot notation.

Cheers,

Eric