JavaScript Nested for loops (5/8)


So I figured out the code fairly well, I just don’t know why it works. In the “if” section, I check if the two arrays are similar, at least that’s how I’m understanding it. Each array has three strings, with only one string in common. To me, that means they are not 100% equivalent and the comparison should be false. But it isn’t. Originally, I logged “myPlaces[myPlacesIndex]===friendPlaces[friendPlacesIndex]” and “true” was shown on the console. Why is that if only ONE of the three strings matches with the other array’s three strings?

Also, as the “if” statement is apparently true, how can “console.log(myPlaces[myPlacesIndex]);” pick out the matching string?

var myPlaces = [‘Berlin’, ‘Nice’, ‘Sao Paulo’];
var friendPlaces = [‘Singapore’, ‘Tokyo’, ‘Berlin’];

for (let myPlacesIndex = 0; myPlacesIndex < myPlaces.length; myPlacesIndex++) {
for (let friendPlacesIndex = 0; friendPlacesIndex < friendPlaces.length; friendPlacesIndex++) {
if (myPlaces[myPlacesIndex]===friendPlaces[friendPlacesIndex]) {


we have two loops, one to loop over myPlaces and another loop to loop over friendPlaces

however, the friendPlaces loop is nested inside the myPlaces loop. Thus for every item/value in myPlaces array, we are going to loop over all the items/values in friendsPlaces.

So the friendPlaces loop will run 3 times, ensuring that if there is a match, it will be found


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