For loops


#1

var myPlaces = [‘Turkey’, ‘USA’, ‘Poland’];
var friendPlaces = [‘Pakistan’, ‘Ghana’, ‘Turkey’];

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

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

if (myPlaces[i] === friendPlaces[j]) {
			console.log('Match: ' + friendPlaces[i]);
  		}

Turkey
Pakistan
Ghana
Turkey
Match: Pakistan
USA
Pakistan
Ghana
Turkey
Poland
Pakistan
Ghana
Turkey

I dont understand here why Match is showing Pakistan here. I was just tryin to play with the code. I thought to change myPlaces[i] to friendsPlaces[i] instead of frinedsPlaces[j]. Now even if i changed it the match result should be Turkey or it should just publish error. But my code is showing result. and I couldnt understand why.


#2

Hi @airasyaqub, the problem is here

You can either write

console.log('Match: ’ + myPlaces[i])

Or

console.log('Match: ’ + friendPlaces[j])

That is the place which is matched, not friendPlaces[i], careful with the counter you write, because the counter i or j refer to the array index. friendPlaces [i] is not the same as friendPlaces [j].


Since you’re searching the condition if:

if (myPlaces [i] === friendPlaces [j])

so, you should print either one of them, not friendPlaces [i].

For example, in your case:

if (myPlaces[i] === friendPlaces[j]) {        //<==== if (myPlaces[0] === friendPlaces[2]), means 'Turkey' === 'Turkey', it's a match, 
    console.log('Match: ' + friendPlaces[j]); // therefore, you need to print myPlaces[0] or friendPlaces[2], not friendPlaces[0], if you pay attention on the i and j counter.
}

Based on my example above, if you choose friendPlaces [i], it will be referred as friendPlaces [0], and friendPlaces[0] is referred to ‘Pakistan’ in friendPlaces Array index position [0], that’s why you have been printing Match: Pakistan through your code.

I hope I can make this clear for you. :slight_smile: