Home > Software design >  Looping through an array and log the value one by one
Looping through an array and log the value one by one

Time:06-08

I just started on an entry level javascript course via Udemy and came across an assignment that I don't really understand even when looking at the provided solution.

Could someone please explain how the solution came to be? I'm lost at how was the solution able to print each individual value instead of grouping Canada and Mexico or Norway, Sweden and Russia together.

const listOfNeighbors = [['Canada', 'Mexico'], ['Spain'], ['Norway', 'Sweden', 'Russia']]


for (let i = 0; i < listOfNeighbors.length; i  ) {
    for (let j = 0; j < listOfNeighbors[i].length; j  ) {
        console.log(listOfNeighbors[i][j]);
    }
    
}

CodePudding user response:

It's because there are 2 loops:

This is the first one:

for (let i = 0; i < listOfNeighbors.length; i  ) {

and this is the second one:

for (let j = 0; j < listOfNeighbors[i].length; j  ) {

You have an array called listOfNeighbors (i is the index that keeps track if which element the loop is currently on) and it is made up of smaller arrays, or an array of arrays as you often hear them called.

So that code is looping through each element in listOfNeighbors and then for each group of neighbors, looping through them.

  • Related