I am studying Javascript, for loop, and trying to put the same elements from two different arrays to another new array. It will print two common elements when I put 'console.log()' outside of For loop, However, if I put 'return console.log()' in if statement, it won't work properly(it shows only [ 'Ray' ].)
I would like to know the difference between them.
I will leave two codes for you. Thank you so much for your help.
//code1
let bobsFollowers = ['Natalia', 'Ray', 'Kay', 'Clau'];
let tinasFollowers = ['Ray', 'Yama', 'Kay'];
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(bobsFollowers[i])
}
}
}
console.log(mutualFollowers)//output: [ 'Ray', 'Kay' ]
//code2
let bobsFollowers = ['Natalia', 'Ray', 'Kay', 'Clau'];
let tinasFollowers = ['Ray', 'Yama', 'Kay'];
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(bobsFollowers[i])
return console.log(mutualFollowers)
}
}
}// output: [ 'Ray' ]