Javascript nested loops for beginners

Hello folks! Why does this code print 1 2, and not the names that are similar in the arrays? Comes from codecademy's JS beginner course
const bobsFollowers = ['Tim', 'Kim', 'Lim', 'Nim'];
const tinasFollowers = ['Kim', 'Nim', 'Hue'];
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(bobsFollowers[i]));
}
}
}
const bobsFollowers = ['Tim', 'Kim', 'Lim', 'Nim'];
const tinasFollowers = ['Kim', 'Nim', 'Hue'];
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(bobsFollowers[i]));
}
}
}
8 Replies
Jochem
Jochem2y ago
take a look at the function definition on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push It says under Return value:
The new length property of the object upon which the method was called.
if you want to log out the follower's name, either outside the loops run console.log(mutualFollowers); or inside the loop where you have it now log out bobsFollowers[i]
Chris Bolson
Chris Bolson2y ago
this both push() and unshift() return the length of the array, not the contents
Å Marlon G
Å Marlon GOP2y ago
Ok, then that makes sense, but why 1 and 2? Is that the indeces of the bobs when tinas match?
Jochem
Jochem2y ago
it's the length of mutualFollowers after the push operation when it runs into Kim, it pushes Kim to the mutualfollowers array and returns 1 for the new length then it runs into Nim, and pushes that to mutualFollowers, and logs out 2 for the number of items in mutualFollowers after pushing Kim and Nim
Å Marlon G
Å Marlon GOP2y ago
Ah! Now I see, so i mixed up index number of each content, and the content number it self. I was expecting the index number of bobs to appear.
Jochem
Jochem2y ago
that's simply not what push returns
Å Marlon G
Å Marlon GOP2y ago
Got it! Thanks! 👏
Jochem
Jochem2y ago
np!
Want results from more Discord servers?
Add your server