5/7 for loops inside of for loops


#1

var myPlaces = [‘sleep’, ‘new job’, ‘Hawaii’];
var friendPlaces = [‘home’, ‘aruba’, ‘jamaica’];

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('Our favorite place in the world is: ’ + ’ ’ + myPlaces[i] + ‘!!!’);
} else {
** console.log(‘There are no places we have in common Christi Pants!!!’);**
** }**

}
}

In the code above, I wanted to have the program log a msg. if arrays: myPlaces and friendPlaces didn’t have anything in common. As you can see, I tried to do an if else and it works; However, it logs the msg. 9 different times. I realize it is because the program checks 9 different times if there is something in common and has to log it according to the script… but what if I only need it to log the msg. once? Thank you!


#2

Hi @hummingcowbird,

There’re many ways to go around as there’re many ways to write the code. But what I would do is create another variable, set it to a Boolean. Give you a heads up, say:

var matched = false;

So when there’s match between myPlaces and friendPlaces, reassign the matched variable with another Boolean.

Lastly, make a condition, if there’s no match found, console.log the script/message you want. That way, it will only show the message once.

Yes, you’re right. Because your if/else statement is wrap inside nested loop. So if you want to print your message once. You will need to do it outside of the loop. Because what we learnt, loop is for doing something repetitively, not exactly what you wanted in this case.

Hope you can figure out how to code it with the hints. Have fun! :slight_smile:


#3

Hi codexthon and thank you for your time.

In VERSION 1 I moved the msg to the outside of the loop and it worked ok. However, When there is a match, the program still logs the match msg and the alternate msg.

In VERSION 2 I added the following code at the end:

if (myPlaces[i] !== friendPlaces[j]){
console.log(‘There are no places we have in common Christi Pants!!!’);
}

It seems to take care of the issue if there is a match. But if there isn’t a match, then nothing gets logged.

In VERSION 3 I , then, added a break on the 6th to last line and it took care of the issue except for when there is a match, both match and alternate msg. get printed. I’ll keep trying. I’ll also look into the variable reassignment possibility. Thank you again. Cheers!

Here’s the code if anyone is interested. It’s not required of the course… I just wanted to know if I could do it.

Version 1

var myPlaces = [‘here’, ‘new job’, ‘Hawaii’];
var friendPlaces = [‘in’, ‘there’, ‘jamaica’]; /*as you can see there are no matches and the alternate msg will log. If there is a match, both match and alternate msgs will log. */

for(var i = 0; i < myPlaces.length; i++){
for(var j = 0; j < friendPlaces.length; j++){
if (myPlaces[i] === friendPlaces[j]){
console.log('Our favorite place in the world is: ’ + ’ ’ + myPlaces[i] + ‘!!!’);
}
}
}
console.log(‘There are no places we have in common Christi Pants!!!’);

VERSION 2

var myPlaces = [‘here’, ‘new job’, ‘Hawaii’];
var friendPlaces = [‘in’, ‘there’, ‘jamaica’];
for(var i = 0; i < myPlaces.length; i++){
for(var j = 0; j < friendPlaces.length; j++){
if (myPlaces[i] === friendPlaces[j]){
console.log('Our favorite place in the world is: ’ + ’ ’ + myPlaces[i] + ‘!!!’);
}
}
}
if (myPlaces[i] !== friendPlaces[j]){
console.log(‘There are no places we have in common Christi Pants!!!’);
}

VERSION 3

var myPlaces = [‘here’, ‘new job’, ‘Hawaii’];
var friendPlaces = [‘in’, ‘there’, ‘jamaica’];
for(var i = 0; i < myPlaces.length; i++){
for(var j = 0; j < friendPlaces.length; j++){
if (myPlaces[i] === friendPlaces[j]){
console.log('Our favorite place in the world is: ’ + ’ ’ + myPlaces[i] + ‘!!!’);
}
break
}
}
if (myPlaces[i] !== friendPlaces[j]){
console.log(‘There are no places we have in common Christi Pants!!!’);
}


#4

Hi @hummingcowbird,

I will give my observations and comments according to versions. Will try to make it short and understandable.

Version 1:

var myPlaces = ['here', 'new job', 'Hawaii'];
var friendPlaces = ['in', 'there', 'jamaica']; 

//Computer reads the first loop, execute codes inside the loop:
for(var i = 0; i < myPlaces.length; i++){
  //This is another nested loop inside a loop, computer will execute all code inside the second loop (nested loop) first
  for(var j = 0; j < friendPlaces.length; j++){
    if (myPlaces[i] === friendPlaces[j]){
      console.log('Our favorite place in the world is: ' + ' ' + myPlaces[i] + '!!!');
    }
  }
  //nested loop finishes, back to the first loop
}
//This will continue until all loop finishes

//Only then, computer will read the next code, no matter how, the code below will get executed and print "There are no places........."
console.log('There are no places we have in common Christi Pants!!!');

The last console.log will be executed as code no matter what, because the computer reads JavaScript from Top to Bottom, the way you write the code in Version 1, computer will finish all the loop then only reach the console.log(('There are no places we have in common....") part. As you just purely write console.log, of course, the console.log will get executed and print the sentences you want.


Version 2:

var myPlaces = ['here', 'new job', 'Hawaii'];
var friendPlaces = ['in', 'there', 'jamaica'];

//Same thing, computer will execute from top to bottom
for (var i = 0; i < myPlaces.length; i++) {
  for (var j = 0; j < friendPlaces.length; j++) {
    if (myPlaces[i] === friendPlaces[j]) {
      console.log('Our favorite place in the world is: ' + ' ' + myPlaces[i] + '!!!');
    }
  }
}
//By this line, the above loop and nested loop inside are all executed. That's why you can print out something IF there's a match

//Until this part, the above loop already finish executed, so the below IF is NOT part of the loop
//Therefore when myPlaces[i] !== friendPlaces[j], is actually undefined !== undefined which equals to false, so the code below will forever NOT get executed
if (myPlaces[i] !== friendPlaces[j]) {
  console.log('There are no places we have in common Christi Pants!!!');
}

You need to understand when you write myPlaces[i] outside of a loop, your i is not defined, because i is only defined inside the for loop statement. Same goes for friendPlaces[j] as j is not defined. You can test this by putting console.log(myPlaces[i]) before your IF statement to see what is printed.

var myPlaces = ['here', 'new job', 'Hawaii'];
var friendPlaces = ['in', 'there', 'jamaica'];

//Same thing, computer will execute from top to bottom
for (var i = 0; i < myPlaces.length; i++) {
  for (var j = 0; j < friendPlaces.length; j++) {
    if (myPlaces[i] === friendPlaces[j]) {
      console.log('Our favorite place in the world is: ' + ' ' + myPlaces[i] + '!!!');
    }
  }
}
//Loop finishes

//What is the value of myPlaces[i]? friendPlaces[j]?
console.log(myPlaces[i]);       // result is undefined
console.log(friendPlaces[j]);   // result is undefined

if (myPlaces[i] !== friendPlaces[j]) {
  console.log('There are no places we have in common Christi Pants!!!');
}

Result:

undefined
undefined

The console.log(myPlaces[i]); and console.log(friendPlaces[j]); will print undefined, so when you test for if (undefined !== undefined), the result is false, therefore the console.log inside will never get executed.

For slightly advance explanation:
(Just in case you wonder, and for completion):
(Ignore this if it’s getting too hard to understand, it’s okay for you to not understand it now)

The leakage of i value using var in for loop statement, means that i = 3 when the loop ends, if you console.log(i), you will get value 3, like below:

var myPlaces = ['here', 'new job', 'Hawaii'];
var friendPlaces = ['in', 'there', 'jamaica'];

//Same thing, computer will execute from top to bottom
for (var i = 0; i < myPlaces.length; i++) {
  for (var j = 0; j < friendPlaces.length; j++) {
    if (myPlaces[i] === friendPlaces[j]) {
      console.log('Our favorite place in the world is: ' + ' ' + myPlaces[i] + '!!!');
    }
  }
}
//Loop finishes

//What is the value of myPlaces[i]? friendPlaces[j]?
console.log(i);                // result is 3;
console.log(j);                // result is 3;
console.log(myPlaces[i]);       // result is undefined
console.log(friendPlaces[j]);   // result is undefined

if (myPlaces[i] !== friendPlaces[j]) {
  console.log('There are no places we have in common Christi Pants!!!');
}

so with that logic, myPlaces[i], i replaced by 3, myPlaces[3] === undefined because there’s no value at index 3 inside array myPlaces. Same goes for j. This leakage is why let is introduced in the ES6 JavaScript newer syntax, where if you console.log(i) after for loop by using let, there’s no leakage value of i, instead an error ReferenceError: i is not defined will be returned.


Version 3:

For Version 3, you’re building a faulty code based on the Version 2, that will get complicated very quickly, just remember when you use break, it will break the loop, important point: think of this, if you have three places in common, when you use break, the loop will be broken and ended at break and the rest of the same places will not get printed anymore because the loop stop running.


Lastly, I would really suggest you to learn how to format your code in your post, refer here, as it will take me or anyone else who wants to help much more time to format your code by copying it and change it one by one because how the forum twisted your code.

Give my suggested solution a go, like I said, there will be different ways to write codes, but I think that solution may be easier to solve your situation. Also, go through the previous exercises, if you’re having trouble with the foundation concepts, it’s better to make clear before you move to the harder ones. I think this is getting very long, that’s all.

:slight_smile:


#5

Hi! I have another question for this excercise :slight_smile:

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

Now I think I do understand what this code does in terms of loops but the last statement, the if one, is confusing. I cannot understand how the text in the console.log will give only the matched elements. How does this work?


#6

Hello codexthon,
Thank you for your reply. That is a lot of great useful info. I certainly appreciate and will heed your suggestions. Thanks again. Cheers!


#7

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