FAQ: Loops - Nested Loops

I’m getting an error for line 3 (const tinasFollowers), and I can’t figure it out.
// Write your code below
const bobsFollowers = [‘John’, ‘Sally’, ‘Fred’, ‘Scooby’];
const tinasFollowers = [‘Ginger’, ‘Fred’, ‘Sally’];
const mutualFollowers = ;

for (let i = 0; i < bobsFollowers.length; i++) {
for (let j = 0; i < tinasFollowers.length; j++) {
if (bobsFollowers[i] === tinasFollowers[j]) {
mutualFollowers.push(tinasFollowers[j]);
}
}
}
console.log(mutualFollowers);

Here is the error:
/home/ccuser/.bin/node: line 3: 248 Killed /usr/bin/node --max-old-space-size=200 $@
It always says line 3, but the # killed changes each time.

Look at the loop condition:

for (let j = 0; i < tinasFollowers.length; j++) {

Thank you! I went over that so many times. Any idea why the error was pointing me to line 3?

That would indicate a runaway loop, perhaps?

This work, but not is correct

// Write your code below
const bobsFollowers = ['Neymar', 'Messi', 'CR7', 'Mbappe']
const tinasFollowers = ['Neymar', 'CR7', 'M. Reus']

let mutualFollowers = []

for(let i = 0; i < bobsFollowers.length; i++) {
  for(let j = 0; j < tinasFollowers.length; j++){
    if(bobsFollowers[i] === tinasFollowers[j]) {
      mutualFollowers = tinasFollowers[j]
      console.log(`Both mutual friends ${mutualFollowers}`)
    }
  }
}

You have initialized mutualFollowers as an empty array [] which is correct.

The problem lies in the statement

mutualFollowers = tinasFollowers[j]

In the above line, you are replacing an array with a string. If you print out mutualFolllowers at the bottom (outside) the nested loops, you will see

} // End of nested loops 

console.log(mutualFollowers)
// Output: 'CR7'

As the instructions mention,

If the current element from the outer loop is the same as the current element from the inner loop, push that element into the mutualFollowers array.

You need to use the .push() method to push values into the existing array.

If you push the strings into the array, then you can confirm that your output will be similar to:

console.log(mutualFollowers)
// Output: [ 'Neymar', 'CR7' ]
2 Likes

My first attempt included an incorrect semicolon at the end of this line:
if (bobsFollowers[i] === tinasFollowers[j]); {
Which resulted in three copies of each element in the first array (bobsFollowers) being pushed to the empty array, including the one non-mutual element.

Removing the semicolon passed the challenge, but I do not understand how that extra semicolon led to the result it did. Can anyone provide an explanation?

The semi-colon token tells the script parser where the end of statement is. Once it reaches that token, it quits parsing and begins interpreting and compiling the code it has read in to that point.

We can see that an if statement has a code block which can run into several lines of code. The statement does not end until the last closing brace, so it follows we would not want any semi-colons outside of the block(s), either before or after.

2 Likes
if (bobsFollowers[i] === tinasFollowers[j]) {
    mutualFollowers.push(bobsFollowers[i]);
}

If the condition is true, the code block between the curly braces is executed i.e. if the condition is true, an element of bobsFollowers is pushed to the mutualFollowers array. If the condition is false, then nothing happens.

Your code (with incorrect semi-colon):

if (bobsFollowers[i] === tinasFollowers[j]); {    // Incorrect semi-colon
    mutualFollowers.push(bobsFollowers[i]);
}

// IS EQUIVALENT TO

if (bobsFollowers[i] === tinasFollowers[j]) {
    // Empty block
}
{  // Separate block not dependent on any condition
    mutualFollowers.push(bobsFollowers[i]);
}

There are 4 elements in bobsFollowers and 3 elements in tinasFollowers. You have a for loop iterating over bobsFollowers and a nested for loop iterating over tinasFollowers.

In every iteration of the outer for loop, the inner for loop runs through three iterations. The if condition is evaluated, but because of the incorrect semi-colon, regardless of whether the condition is true or false, no block of statements is executed. The block of code with the push statement is not a part of the if statement, but a completely separate block. So, in each iteration an element of bobsFollowers is pushed to mutualFollowers resulting in three copies of each element of the outer loop being pushed into the mutualFollowers array.

2 Likes

Thank you!! That is a very helpful explanation

1 Like

Hi,

When I have two arrays with differents lengths, should I put the larger in the outher loop? And the result of the same followers should be made considering the larger array?

Thanks!

It should not matter which loop the larger array is iterated in given that all the values will be accessed, regardless of order. It will not have any effect on the Big O evaluation of the code (n^2, either way).

// Write your code below const bobsFollowers = ["Fred", "Jack", "Kevin", "Steven"]; const tinasFollowers = ["Jack", "Zack", "Kevin"]; const mutualFollowers = []; for (let i = 0; i < bobsFollowers.length; i ++) { for (let j = 0; j < tinasFollowers.length; j ++) { if (bobsFollowers[i] === tinasFollowers[j]) { mutualFollowers.push(bobsFollowers[i]); } } }; console.log(mutualFollowers);

I got the same error. I thought I was suppose to use const for arrays? Also, arent const suppose to be uppercase?

Can you share a screenshot showing your code and the error/feedback message?

Perhaps the extra space in i ++ and j ++ is causing the issue,

// You wrote:
for (let i = 0; i < bobsFollowers.length; i ++) {

// Try changing to:
for (let i = 0; i < bobsFollowers.length; i++) {

OMG that was exactly it. SMH Appreciate the help!

Perhaps this is what you are looking for


Hi​:sweat_smile: could someone please explain why i’m getting the values 1 & 2 in my console? i’ve been going over my code for ages trying to figure out what i’ve done wrong and my mind is blanking!! thank u in advance :slight_smile:

Your console.log statement nested inside the loops is printing the return value of the push method.

The documentation of a programming language is a very useful resource to learn more about the parameters, return values and details about methods and other features of the language.

From the documentation of the push method (Array.prototype.push() - JavaScript | MDN),

scrn1

1 Like

OMG thank you! that completely went over my head you’re a life saver :blush:

1 Like

Hi guys. can anyone explain why we need to use the nested loop? because i tried the non nested loop and still get the same result.

const bobsFollowers = [‘Neymar’, ‘Messi’, ‘CR7’, ‘Mbappe’]
const tinasFollowers = [‘Neymar’, ‘Messi’, ‘M. Reus’]
const mutualFollowers =
for (let i = 0; i < bobsFollowers.length;i++){
if (bobsFollowers[i] === tinasFollowers[i]){
mutualFollowers.push(bobsFollowers[i])
}
}
console.log(mutualFollowers)

thanks in advance