Why is the console returning array items so many times?


#1

Sorry if this is obvious, but I am a complete noob. I just don’t understand why this is happening on exercise 7/5:

https://www.codecademy.com/courses/learn-javascript/lessons/loops/exercises/for-loops-iii?action=lesson_resume

I don’t understand why the console is returning the items from the arrays multiple times.

My code:

var myPlaces = ['Thailand', 'Australia', 'Japan'];
var friendPlaces = ['Australia', 'Canada', 'Mexico'];

for (var i = 0; i < myPlaces.length; i++) {
  console.log(myPlaces[i])
  
  for (var j = 0; j < friendPlaces.length; j++) {
    console.log(friendPlaces[j]);
    }
  }

Output:

Thailand
Australia
Canada
Mexico
Australia
Australia
Canada
Mexico
Japan
Australia
Canada
Mexico

As you can see every item is repeated 3 times and in a, seemingly to me, random order. Except for “Japan”. I’m so confused as to why this is happening. What am I missing here?


#2

You have a loop within a loop when you should have two separate loops.
The order isn’t random

It logs the zero index in myPlaces then every index in friendPlaces. The first index of myPlaces then every index of friendPlaces so on and so forth.


#3

I see. Thank you. I guess I was just confused because I was analyzing the output in the middle of the exercise. The loop was within the loop because the ultimate goal was to compare the items in the array and output the ones that match. Thanks for clearing that up so quickly.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.