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 [email protected]
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