FAQ: Why can't I console log mutualfollowers.push()

So I’ve been seeing a lot of variations of this question and it requires a fundamental understanding of what array.push() does. This link: .push syntax shows the syntax of the method.
array.push(element1, ...)

  • So it takes an array, you’ll usually be using a different variable name and in the case of this lesson mutualfollowers
  • Next it needs element1 or potentially more, these are the targets that will get pushed into your array.
  • Final key detail from the documentation: " Return value: The new length property of the object upon which the method was called."

This final part is why console.log(mutualFollowers.push(bobsFollowers[i]) doesn’t work as expected. It is logging the length of mutualFollowers since that is the return of .push(). If you just want to log the array, all you need is console.log(mutualFollowers).

I hope this helps! Feel free to discuss this further and help each other below!

8 Likes

Struggling to print this to the console as a String - it only prints numbers (1 and 2). Im not sure what I am doing wrong, any ideas? code below

const bobsFollowers = [‘john’, ‘sam’, ‘chris’,‘pen’]
const tinasFollowers = [‘john’, ‘michelle’, ‘sam’]
const mutualFollowers =
for (let i = 0; i < bobsFollowers.length; i++) {
for (let j = 0; j < tinasFollowers.length; j++) {
if (bobsFollowers[i] === tinasFollowers[j]) {
console.log(mutualFollowers.push(i))
}
}
}

2 Likes

First of all, with mutualFollowers.push(i), you are pushing a number from the for loop into the empty array, not the actual value of one of the arrays. So it either needs to be mutualFollowers.push(tinasFollowers[j]) or mutualFollowers.push(bobsFollowers[i])

Next, if you console.log the push, you are actually returning the output of the .push method, which will always return the LENGTH of the array you are pushing into.

JavaScript Array push() Method
Return Value: A Number, representing the new length of the array

So when the nested loop gets a match, it will push the number (or the name, that doesn’t matter) in the array, and it will return the length of the array, which is now 1. Then it happens again at the second match and it will return the length 2.

var animals = ['pigs', 'goats', 'sheep'];

console.log(animals.push('cows'));
// expected output: 4
7 Likes

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

Is there a way to get the value of the index and use that string in the output? So this is my code:

let bobsFollowers = ['Linda', 'Gene', 'Tina', 'Teddy'];
let tinasFollowers = ['Jimmy Jr.', 'Linda', 'Gene'];
let mutualFollowers = [];

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

It works, but prints
Both are friends with: 1
Both are friends with: 2

I’ve tried searching around different websites but haven’t found anything that prints out their names instead yet. It’s not something I desperately need to solve, but I’m curious.

This expression is concatenating a string value but that value is the return from the push method, which is the new length of the array, hence, a number.

1 Like

I had the same issue as a number of the others. I was expecting to see the mutual strings in my output:

// Write your code below

const bobsFollowers = ['Jenni', 'Dave', 'Greg', 'Valerie'];
const tinasFollowers = ['Heather', 'Jenni', 'Dave'];

let mutualFollowers = [ ];

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

And then it occurred to log the new array on its own and it printed the names for me, which also gave me the mutuals plus and ‘undefined’ result that needed an additional tweak in the loop to get rid of.

Does this constitute the correct approach?

This is combining two operations in one. Is it necessary to log while looping?

1 Like

No, I suppose not. I could just drop the first console.log part inside the loop and as long as I keep the act of pushing to the mutualFollowers array in there.

Because like I had it, the output was:

1
2
[ ‘Jenni’, ‘Dave’ ]

But if I just cut out the logging part inside the loop, I get just the mutual array contents without the counting data:

[ ‘Jenni’, ‘Dave’ ]

2 Likes

(Which I guess makes more sense).

1 Like

Hi all,

For some reason, when I run my code below, it only prints to the console an empty array “

Could someone tell me why I can’t print to the console the names of the matching followers? I’ve looked all over the forums and I can’t figure out what’s incorrect in my code.

Thanks.

const bobsFollowers = ['John', 'Josh', 'James', 'Jacob'];
const tinasFollowers = ['Sarah', 'John', 'Jacob'];
let mutualFollowers = [ ];

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

.push is a method, calling a method requires parentheses, not square brackets

1 Like

One thing that is somewhat annoying and will throw an error in completing this task is that the software for codecademy wants you to use the same variables (i and j) which the code doesn’t need to run it properly (I used b and t, for bob and tina)

But for everyone asking how to log the names and not the numbers… anytime you want to reference the data that is stored in the array and not just the index number make sure you do a separate console.log(). there is no need to log every iteration of the loop but if you wanted it to do so… make it a separate command in the codeblock or do it after the loop has completed and put it at the very end of the code that needs to run.
e.g.
let bobsFollowers = [‘Bobby’, ‘Robby’, ‘Throbby’, ‘Moe’];
let tinasFollowers = [‘Bobby’, ‘Steve’, ‘Throbby’];
let mutualFollowers =;
for (b = 0; b < bobsFollowers.length; b++){
for (t = 0; t < tinasFollowers.length; t++) {
if (bobsFollowers[b] === tinasFollowers[t]) {
mutualFollowers.push(tinasFollowers[t])
}
}
}
console.log(Our mutual followers are: ${mutualFollowers})
//output: Our mutual followers are: Bobby,Throbby

it actually works…

console.log(mutualFollowers.push(bobsFollowers[i])); // prints Number of items that mutualFollowers has

let’s break down …

  1. so we want to print in to the console, let’s see
    2.ok we have mutualFollowers with push() method , that means we want to copy something to to mutualFollowers and this is bobsFollowers[i]
  2. alright , we copy bobsFollowers[i] and printed a number… humm curious , where the number com from? It looks like .log is printing the number of items that mutualFollowers has after pushing this one…
    Ok it might be confusing… so lets see the code
const bobsFollowers = ['Ric', 'Mick', 'Ammy', 'Jonny', 'Joana'];
const tinasFollowers = ['Ammy', 'Jonny', 'Lyll', 'Joana'];
// we have 3 identical names ['Ammy', 'Jonny', 'Joana'] 
const mutualFollowers = []; // after loop it will get those 3 values
for (let i = 0; i < bobsFollowers.length; i++) {
  for (let j = 0; j < tinasFollowers.length; j++){
   if (bobsFollowers[i] === tinasFollowers[j]){

     console.log(mutualFollowers.push(bobsFollowers[i])); //will do two things
      // 1. copy first identical follower to mutualFollowers
     // 2. print to console number representing items that ate in that variable , witch is 1 after .push first one
     console.log(`Index of bobsFollower: ${bobsFollowers[i]} is ${bobsFollowers.indexOf(bobsFollowers[i])}`); // for test purposes we will print name of the follower and the Index, to see if it is correct 
    }  
  }
}
console.log(mutualFollowers); // will print [ 'Ammy', 'Jonny', 'Joana' ]

// now try to use this code to see what will happen
console.log(mutualFollowers.push(tinasFollowers[5]));
console.log(mutualFollowers.pop());

console.log(`How manny items mutualFollowers has: ${mutualFollowers.length}`);
console.log(mutualFollowers);

console.log(`How manny items mutualFollowers has: ${mutualFollowers.push(tinasFollowers[5])}`);
console.log(mutualFollowers);

conclusion: mostly we use console.log for testing purposes, it’s good to logically understand why it gives you that output, so we can understand behavior of other methods and correct the code to get the right result.

No cool at all to spend two hours getting errors just for having a extra t on .length!

This keep happening to me… one extra comma or misspelling and the code gives errors. :frowning:

There is another solution and it works well, but unfortunately it’s not accepted by codecademy in this task…

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

Only problem with this is mutualFollowers is not defined in the above code sample. We are left to assume,

let mutualFollowers = [];

appears somewhere above this sample in the complete code. That stipulated, we could rationalize that at this point there is no .push() method on Array class objects.

Algorithm wise it is sound, though. To emulate .push your code need only return the length of the mutualFollowers array.

return mutualFollowers.length;

but since the sample is not a function, that is not doable.

let m = mutualFollowers;    // create symbol from long name

let b = bobsFollowers;

let t = tinasFollowers;

If there is ever any question what b , m, and t are, we need only look up in the source code for definition. Long names are useful in the big picture, but in the mechanics they serve little use.

    let i = 0; j;
    for (i; i < b.length; i++) {
        let x = b[i];
        for (j = 0; j < t.length; j++) {
            x === t[j] ? m.push(x) : null;
        }
    }

Sneaky how a ternary expression can lessen the burden from time to time. This one does something on true, and nothing on false. One expression, and no if statement.

The console will respond with null if the last comparison is false, and with the length of mutualFollowers array if the it is true. This goes right back to what Chris said in the OP. .push() returns the array size.

Convince me that the above symbol approach is not easier to read with the same purpose in mind.

Were we to write it without .push(),

    let k = 0;
    ...
        m[k++] = x

Your algorithm refactors beautifully. With no push. But there is a shove. We still need to apply the condition.

m[k++] = x === t[j] ? x : null;

m is rather unruly, though,

["john", null, null, null, null, null, null, null, null, null, null, "sam"]

A quick fix with an iterator,

console.log(m.filter(x => x && true))  // null undefined 0 NaN "", all fail
["john", "sam"]

but then, if we don’t have push, we don’t have filter, either. Seems we’re working backward, but it is a worthwhile exercise.

Say we do have filter…

console.log(m.filter(x => !! x))
["john", "sam"]