JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Build a Quiz Challenge, Part 1 Solution

Jason Hill
Jason Hill
Full Stack JavaScript Techdegree Student 11,399 Points

Confused on the for loop, declaring "i". Want to ensure I am understanding.

So I am trying to understand why dave has used the following when creating a for loop. I think I am just having an issue grasping for loops and the reason why we are using "i", is it just arbitrary to initialize the loop? Dave used below. I was able to do this challenge with if, and else if. I started with a for loop, but got confused half way through.

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

If I am getting this correctly, we are

  1. creating variable i making it 0
  2. checking if i is less than questions array length, it is, so run code below
  3. making question equal to questions array index of [i, at the moment 0]"[0]
  4. adding 1 to i so it stops after getting to a length longer than the array indexes
  5. making answers = questions array index [i, at the moment 0][1]
  6. making response = prompt(question)

Then it runs again, increasing i, thus moving the question over one index, the answer over one index, and again. So my understanding is that we use i to start the loop and set to zero, and it allows us to use [i] in place of the actual index number to iterate through each variable in the loop? As i increases, it automatically adjusts the rest of code to that value?
Thanks for help!

1 Answer

In short we use loops to iterate over a group of elements, array, object, string and more. we set the ā€œiā€ in order to keep track in which iteration we are if are in the first iteration, the i is equal to zero - question[0]. in this example we are iterating over multi - dimensional array, in order to access each question and answer we need to use [] notation. so as we said i represent in which iteration the loop is, so in order to access the question which in index 0 in the array in each iteration we need to say question[i][0] which is like saying question[0][0] because the loop in his first iteration.