2 questions about array and iteration in JS

2 questions about array and iteration in JS
0

#1

When doing exercise 12 of chapter 20 of
’A Smarter Way to Learn JavaScript’

The question says:

Here are 4 lines of code.
var animals = [“goat”, “cat”, “crow”];
var products = [“milk”, “cheese”, “burger”];
var foodItems = [];
var k = 0;
Continue the code to create nested loops. The inner loop concatenates each of the elements of animals with each of the elements of products, with no space separating them. Accumulate the combinations in foodItems. The counter for foodItems is k. Limit the number of loops by the length of each array.

The answer is:

for (var i = 0; i < animals.length; i++) {
  for (var j = 0; j < products.length; j++) {
    foodItems[k] = animals[i] + products[j];
    k++;
  }
} 

I could not understand:
1- The difference of writing “fodItems[k]”, “[k]”, or just “k”. Same for the other counters i and j.
2- Why did we add k++ at the end what is the purpose?.
3- Any idea about the outcome of this code?


#2

foodItems[k] represents an element in the kth index of the array. k represents the index of the array, “k” is just a string with value “k”

The instructions said k is a counter, so k++ increments k by 1 each time a new string concatenated string is added in the previous line before the k++.

When this code finishes, k will be 8 (which represents the number of items added to the foodItems array. Also, the foodItems array will contain the following 8 items:

[ ‘goatmilk’,
‘goatcheese’,
‘goatburger’,
‘catmilk’,
‘catcheese’,
‘catburger’,
‘crowmilk’,
‘crowcheese’,
‘crowburger’ ]