Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looping through an array and log the value one by one

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]);
    }
    
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading